【发布时间】:2015-07-10 20:50:44
【问题描述】:
我有以下代码,我正在尝试比较一些值并返回最高值:
def high(it):
it = iter(it)
returnlist = []
try:
while True:
one = next(it)
two = next(it)
three = next(it)
if three <= two and one <= two:
returnlist.append(two)
except StopIteration:
pass
return returnlist
它工作了一半,但不正常:
>>high([0,1,-1,3,8,4,3,5,4,3,8]) #(this works)
[1, 8, 5]
>>high([5,2,4,9,6,1,3,8,0,7]) #(this doesn't work, should return [9,8]
[8]
>>high(int(is_prime(p)) for p in irange(1,20)) #(doesn't work, returns four 1's - should return 5)
[1, 1, 1, 1]
【问题讨论】:
-
second未在您的行中定义return list.append(second)我假设它是two而不是second -
单步执行你脑海中的代码,你会发现问题所在。
-
请记住,在循环的每次迭代中,迭代器都会前进三个位置。所以你只是在比较元素 [0,1,2]、[3,4,5]、[6,7,8] 等,而不是每组相邻的 3。
-
您正在做的事情可以由
for one, two, three in zip(it, it, it):完成。如果您需要遍历窗口而不是块,则需要以某种方式跟踪最后两个值,无论是显式还是其他方式。 (itertools文档中的pairwise配方演示了一种简单的隐式方法。) -
@heinst 你是对的!改了,谢谢:-)