这里有两个(我认为)应该做同样的事情,但实际上没有。在
似乎在列表理解中,获取的索引是第一个可以对应的索引,因此,当您在不同的索引中有相同的值时,就会出现歧义。在
有没有方法可以修改filter2
中的列表理解,从而得到与filter1
中相同的结果?在
L = [98.75011926342906,
97.8178200008178,
98.6138182016438,
98.55520874507613,
98.25262038791283,
98.75011926342906,
99.06770073738875,
98.66970163697574,
98.56611283001895,
98.47751713985852,
98.66970163697574,
97.8178200008178]
def filter1(L, threshold=98.7):
items = []
for i in range(len(L)):
if L[i] < threshold:
items.append(i)
return items
def filter2(L, threshold=98.7):
items = [L.index(x) for x in L if x <= threshold]
return items
print filter1(L)
>>> [1, 2, 3, 4, 7, 8, 9, 10, 11]
print filter2(L)
>>> [1, 2, 3, 4, 7, 8, 9, 7, 1]
您可以使用enumerate,它将循环的位置指定给i,x被指定为当前值。在
您可以在此处使用
enumerate
作为助手:enumerate
将为您提供两对{x <= threshold
,则只取i
。在之所以使用索引7而不是10,是因为有重复的元素,并且index返回值所在的最小索引。此外,搜索索引也需要线性时间。你的整个循环都是二次的。在
相关问题 更多 >
编程相关推荐