如何分别在Python和Perl中执行for()或foreach()循环,只打印每第三个索引?我需要将每个第三个索引移动到一个新数组中。如何在Perl或Python中只打印每三个索引?
回答
的Python
print list[::3] # print it
newlist = list[::3] # copy it
的Perl
for ($i = 0; $i < @list; $i += 3) {
print $list[$i]; # print it
push @y, $list[$i]; # copy it
}
的Python:
for x in a[::3]:
something(x)
美丽。 Python切片给我勃起。 – 2009-09-23 09:35:52
http://en.wikipedia.org/wiki/Diphallia? – u0b34a0f6ae 2009-09-23 13:22:39
在Perl:
$size = @array;
for ($i=0; $i<$size; $i+=3) # or start from $i=2, depends what you mean by "every third index"
{
print "$array[$i] ";
}
的Perl 5.10新state变量是非常方便的位置:
my @every_third = grep { state $n = 0; ++$n % 3 == 0 } @list;
另外请注意,您可以提供的元素列表切片:
my @every_third = @list[ 2, 5, 8 ]; # returns 3rd, 5th & 9th items in list
您可以动态创建使用map这片名单(见Gugod的优秀的answer)或子程序:
my @every_third = @list[ loop(start => 2, upto => $#list, by => 3 ) ];
sub loop {
my (%p) = @_;
my @list;
for (my $i = $p{start} || 0; $i <= $p{upto}; $i += $p{by}) {
push @list, $i;
}
return @list;
}
更新:
关于runrig的评论......这是 “单向”,使之成为环内工作:
my @every_third = sub { grep { state $n = 0; ++$n % 3 == 0 } @list }->();
的Perl:
与draegtun的回答,但使用计数变量:
my $i;
my @new = grep {not ++$i % 3} @list;
并且可以很好地放在一个do块中:my @new = do {my $ i; grep {not ++ $ i%3} @list}; – draegtun 2009-09-23 12:45:36
@array = qw(1 2 3 4 5 6 7 8 9); print @array[(grep { ($_ + 1) % 3 == 0 } (1..$#array))];
的Perl:
# The initial array
my @a = (1..100);
# Copy it, every 3rd elements
my @b = @a[ map { 3 * $_ } 0..$#a/3 ];
# Print it. space-delimited
$, = " ";
say @b;
你可以在Perl做一个切片。
my @in = (1..10);
# need only 1/3 as many indexes.
my @index = 1..(@in/3);
# adjust the indexes.
$_ = 3 * $_ - 1 for @index;
# These would also work
# $_ *= 3, --$_ for @index;
# --($_ *= 3) for @index
my @out = @in[@index];
- 1. 如何在Perl中引用打印?
- 2. 在Python中打印元组索引
- 3. Python - 只打印'打印'
- 4. 如何在Perl打印值
- 5. PHP每个或每个打印数据
- 6. 打印出每一个第三个字母Python
- 7. 打印每句第三字
- 8. 每三个时间,打印此
- 9. 打印在Perl中
- 10. lldb/Xcode:如何打印线索索引,id或名字?
- 11. 如何打印出每个三个数字(偶数和奇数)?
- 12. 如何打印索引或获取ArrayList中项目的项目
- 13. 如何打印或回显PHP中的数组索引
- 14. 如何在每行和每列中添加值并在Perl中打印最后?
- 15. 在java中每三个整数打印一个新行
- 16. 如何在for循环中打印某个索引?
- 17. 如何在Perl中打印BOLD文本?
- 18. 打印在Perl
- 19. 如何在三角形中打印*?
- 20. 如何只打印一次字符串中的每个字母
- 21. Python字符串索引/打印错误
- 22. 如何在perl中垂直打印2d阵列中的每个阵列
- 23. 如何在Perl中打印散列(或其元素)?
- 24. 如何在Perl中访问和打印3或4维散列?
- 25. 如何打印大于0的连续整数,每行三个?
- 26. perl dancer:foreach在模板中只打印第一个值
- 27. 只打印每个组的第一页
- 28. 每行只能打印5个项目
- 29. 如何让Perl和Python打印正在执行的程序的每一行?
- 30. 如何打印索引位置x86 Assemby
@friedo:感谢修复:) – tuergeist 2009-09-23 19:50:26