我试图用列表中每个元组的总和来压缩此列表,然后对其进行过滤,以便只有总和大于0的元组在列表中。此时,使用下面给出的测试代码,在行" ----打印0"之上的随机元组之后不会打印任何内容。我错过了什么?
sub filter_random_4_toops_by_sum {
my ($toops, $thresh) = @_;
my @toops1 = ();
@toops1 = $toops;
my @sorted_toops = ();
my @sortedReturn = ();
my @filtered_toops = ();
@sorted_toops = map{[$_, sum(@$_)]} @toops1;
@filtered_toops = grep {$_[1]> $thresh} @sorted_toops;
@sortedReturn = map{$_->[0]} @filtered_toops;
return \@sortedReturn;
}
测试代码:
sub test_step_4 {
my($sn)= 1;
my $toops = gen_random_4_toops(1, 100, 5);
print "---- random 4-toops:\n";
foreach(@{$toops}) {
print "toop $sn:\t(@{$_});\n and sum = " . sum(@{$_}) . "\n";
$sn++;
}
my $thresh = 55;
print "\n---- random 4-toops filtered by sum above $thresh:\n";
my $filtered_toops = filter_random_4_toops_by_sum($toops, $thresh);
$sn = 1;
foreach(@{$filtered_toops}) {
print "toop $sn:\t(@{$_}); sum = ". sum(@{$_}) . "\n";
$sn++;
}
}
测试代码应输出:
---- random 4-toops:
toop 1: (49 49 4 64); sum = 166
toop 2: (-2 16 57 76); sum = 147
toop 3: (-94 93 -48 85); sum = 36
toop 4: (19 -47 14 38); sum = 24
toop 5: (-57 80 -60 -35); sum = -72
---- random 4-toops filtered by sum above 0:
toop 1: (19 -47 14 38); sum = 24
toop 2: (-94 93 -48 85); sum = 36
toop 3: (49 49 4 64); sum = 166
toop 4: (-2 16 57 76); sum = 147
相当于我在Python(工作)中尝试做的事情:
def filter_random_4_toops_by_sum(toops, thresh):
summit = 0
s = []
for i in toops:
# pdb.set_trace()
summit = 0
for d in xrange(0,4):
summit += i[d]
s.append(summit)
# pdb.set_trace()
together = zip(toops, s)
filtertog = [i for i in together if i[1] > 0]
toops = [x[0] for x in filtertog]
return toops
答案 0 :(得分:1)
@toops1
总是只有一个元素。
@toops1 = $toops;
应该是
@toops1 = @$toops;
但为什么不直接使用@$toops
而不是复制所有元素?
sub filter_random_4_toops_by_sum {
my ($toops, $thresh) = @_;
my @sorted_toops = map { [ $_, sum(@$_) ] } @$toops;
my @filtered_toops = grep { $_[1] > $thresh } @sorted_toops;
my @sortedReturn = map { $_->[0] } @filtered_toops;
return \@sortedReturn;
}
甚至
sub filter_random_4_toops_by_sum {
my ($toops, $thresh) = @_;
return [
map { $_->[0] }
grep { $_[1] > $thresh }
map { [ $_, sum(@$_) ] }
@$toops
];
}
甚至
sub filter_random_4_toops_by_sum {
my ($toops, $thresh) = @_;
return [ grep { sum(@$_) > $thresh } @$toops ];
}