2009-09-23 56 views

回答

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 
} 
+0

@friedo:感謝修復:) – tuergeist 2009-09-23 19:50:26

8

的Python:

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

美麗。 Python切片給我勃起。 – 2009-09-23 09:35:52

+3

http://en.wikipedia.org/wiki/Diphallia? – u0b34a0f6ae 2009-09-23 13:22:39

2

在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] "; 
} 
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 }->(); 
+0

狀態很好。但是如果你不止一次地執行那條線,它將只在第一次工作,除非列表長度是3的倍數。 – runrig 2009-09-23 15:09:22

+0

很好地指出。它的狀態變量稍微令人討厭但並不令人驚訝,它可以通過封裝在匿名子文件中來解決(請參閱我的更新)。 – draegtun 2009-09-23 18:33:47

+1

爲什麼不做'map {$ _ * 3} 0 .. $ MAX/3'並將其用於切片索引? – 2009-09-23 18:35:58

16

的Perl:

與draegtun的回答,但使用計數變量:

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

並且可以很好地放在一個do塊中:my @new = do {my $ i; grep {not ++ $ i%3} @list}; – draegtun 2009-09-23 12:45:36

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