如何只打印Perl或Python中的每个第三个索引?

时间:2009-09-23 09:27:09

标签: python arrays perl

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

8 个答案:

答案 0 :(得分:16)

<强>的Perl:

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

my $i;
my @new = grep {not ++$i % 3} @list;

答案 1 :(得分:12)

的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
}

答案 2 :(得分:9)

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 }->();

答案 3 :(得分:9)

的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;

答案 4 :(得分:8)

的Python:

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

答案 5 :(得分:5)

你可以在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];

答案 6 :(得分:3)

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] ";  
} 

答案 7 :(得分:1)

@array = qw(1 2 3 4 5 6 7 8 9);
print @array[(grep { ($_ + 1) % 3 == 0 } (1..$#array))];