Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print only every third index in Perl or Python?

How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.

like image 842
csyprv Avatar asked Sep 23 '09 09:09

csyprv


2 Answers

Perl:

As with draegtun's answer, but using a count var:

my $i;
my @new = grep {not ++$i % 3} @list;
like image 151
Adam Bellaire Avatar answered Nov 08 '22 14:11

Adam Bellaire


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
}
like image 12
tuergeist Avatar answered Nov 08 '22 16:11

tuergeist