在Python中的列表中获取列表推导的索引

Nat*_*tha -1 python list-comprehension

这是两个功能(我认为)应该做同样的事情但实际上不做.

似乎对于列表理解,所采用的索引是第一个可以对应的索引,因此当您在不同索引处具有相同的值时,存在歧义.

有没有办法修改列表理解,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]
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 5

你可以enumerate在这里用作帮助:

bad_items = [i for i, x in enumerate(L) if x <= threshold]
Run Code Online (Sandbox Code Playgroud)

enumerate会给你一对(index, value)你可以在理解中解压缩
(成i, x).然后你只需要ix <= threshold.