0
我試圖用列表中每個元組的總和壓縮此列表,然後對其進行過濾,以便只有列表中總和大於0的元組才被列入。在這一點上,使用下面給出的測試代碼,在「----打印0以上的隨機元組」之後沒有任何內容會打印出來。我錯過了什麼?根據「Tuple」中的第二個元素進行過濾
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
謝謝,這是信息和有益的,最重要的是正確的。 –