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

csy*_*prv 6 python arrays perl

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

Ada*_*ire 16

Perl的:

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

my $i;
my @new = grep {not ++$i % 3} @list;
Run Code Online (Sandbox Code Playgroud)

  • 并且可以很好地放入一个阻止:我的@new = do {my $ i; grep {not ++ $ i%3} @list}; (8认同)

tue*_*ist 12

蟒蛇

print list[::3] # print it
newlist = list[::3] # copy it
Run Code Online (Sandbox Code Playgroud)

Perl的

for ($i = 0; $i < @list; $i += 3) {
    print $list[$i]; # print it
    push @y, $list[$i]; # copy it
}
Run Code Online (Sandbox Code Playgroud)


dra*_*tun 9

Perl 5.10新的状态变量非常方便:

my @every_third = grep { state $n = 0; ++$n % 3 == 0 } @list;
Run Code Online (Sandbox Code Playgroud)


另请注意,您可以提供要切片的元素列表:

my @every_third = @list[ 2, 5, 8 ];  # returns 3rd, 5th & 9th items in list
Run Code Online (Sandbox Code Playgroud)

您可以使用map(参见Gugod的优秀答案)或子程序动态创建此切片列表:

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;
}
Run Code Online (Sandbox Code Playgroud)


更新:

关于runrig的评论......这是让它在循环中工作的"单向方式":

my @every_third = sub { grep { state $n = 0; ++$n % 3 == 0 } @list }->();
Run Code Online (Sandbox Code Playgroud)


小智 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;
Run Code Online (Sandbox Code Playgroud)


Raf*_*ird 8

蟒蛇:

for x in a[::3]:
   something(x)
Run Code Online (Sandbox Code Playgroud)

  • 美丽.Python切片让我勃起. (3认同)

Bra*_*ert 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];
Run Code Online (Sandbox Code Playgroud)