如何在Perl或Python中仅打印每三个索引?

如何在Perl或Python中仅打印每三个索引?,python,arrays,perl,Python,Arrays,Perl,如何分别在Python和Perl中执行for()或foreach()循环,只打印三分之一的索引?我需要将每三个索引移动到一个新数组。Python: for x in a[::3]: something(x) 蟒蛇 Perl ($i=0;$i

如何分别在Python和Perl中执行for()或foreach()循环,只打印三分之一的索引?我需要将每三个索引移动到一个新数组。

Python:

for x in a[::3]:
   something(x)
蟒蛇

Perl

($i=0;$i<@list;$i+=3)的
{
打印$list[$i];#打印它
按@y,$list[$i];#复制它
}
在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] ";  
} 
$size=@array;
对于($i=0;$iPerl 5.10),新变量在这里非常方便:

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
您可以使用(参见Gugod's Excellate)或子例程动态创建此切片列表:

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;
}
Perl:

与draegtun的答案一样,但使用计数变量:

my $i;
my @new = grep {not ++$i % 3} @list;
@数组=qw(123456789); print@array[(grep{($#+1)%3==0}(1..$#array)); Perl:


您可以用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];

很漂亮。Python切片让我勃起。并且可以很好地放在do块中:my@new=do{my$i;grep{not++$i%3}@list};state很好。但是如果你不止一次执行那一行,它只会在第一次运行,除非列表长度是3的倍数。这一点很好指出。它的状态变量有点烦人,但并不奇怪,你可以通过封装在一个匿名子中来绕过它(参见我的更新)。为什么不
映射{$\u*3}0..$MAX/3
并将其用于切片索引?确实,为什么不呢。事实上,我已经在这一点上对Gugod的答案进行了投票;-)我没有使用map,因为这里已经有一个类似的答案,但由于某种原因,它现在被删除了?@friedo:感谢修复:)
my @every_third = sub { grep { state $n = 0; ++$n % 3 == 0 } @list }->();
my $i;
my @new = grep {not ++$i % 3} @list;
@array = qw(1 2 3 4 5 6 7 8 9); print @array[(grep { ($_ + 1) % 3 == 0 } (1..$#array))];
# 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;
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];