这里有两个功能(我认为)应该做同样的事情,但实际上没有。在Python中的列表中获取列表理解索引
看来,在列表理解的情况下,所采用的索引是第一个可以对应的索引,因此当您在不同索引处具有相同的值时,就会出现歧义。
有没有办法修改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]
将来要注意的小点。我的意思是在'filter1'中使用'<'符号,在'filter2'中使用'<='。结果也不同,因为这两个过滤器使用不同的逻辑,'index'返回找到的第一个索引的值(这是缺陷的位置)。 –