在Python中使用列表理解获取索引

2024-04-29 11:09:59 发布

您现在位置: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]

Tags: 方法in列表forthresholdreturnifdef
3条回答

您可以使用enumerate,它将循环的位置指定给i,x被指定为当前值。在

def filter2(L, threshold=98.7):
    items = [i for (i, x) in enumerate(L) if x <= 98.7]
    return items

您可以在此处使用enumerate作为助手:

bad_items = [i for i, x in enumerate(L) if x <= threshold]

enumerate将为您提供两对{},您可以在理解中将其解压为{}。如果x <= threshold,则只取i。在

之所以使用索引7而不是10,是因为有重复的元素,并且index返回值所在的最小索引。此外,搜索索引也需要线性时间。你的整个循环都是二次的。在

相关问题 更多 >