在Python中查找列表中匹配元素的索引

Log*_*ang 27 python indexing list find

我有一长串的浮点数,范围从1到5,称为"平均值",我想返回小于或大于b的元素的索引列表

def find(lst,a,b):
    result = []
    for x in lst:
        if x<a or x>b:
            i = lst.index(x)
            result.append(i)
    return result

matches = find(average,2,4)
Run Code Online (Sandbox Code Playgroud)

但令人惊讶的是,"匹配"的输出中有很多重复,例如[2, 2, 10, 2, 2, 2, 19, 2, 10, 2, 2, 42, 2, 2, 10, 2, 2, 2, 10, 2, 2, ...].

为什么会这样?

Mar*_*ers 55

您使用的.index()只会在列表中找到您的第一个值.因此,如果索引2和索引9处的值为1.0,则无论列表中出现多少次,.index(1.0)都将始终返回.21.0

用于enumerate()为循环添加索引:

def find(lst, a, b):
    result = []
    for i, x in enumerate(lst):
        if x<a or x>b:
            result.append(i)
    return result
Run Code Online (Sandbox Code Playgroud)

您可以将其折叠为列表解析:

def find(lst, a, b):
    return [i for i, x in enumerate(lst) if x<a or x>b]
Run Code Online (Sandbox Code Playgroud)