簡體   English   中英

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

[英]Finding the indices of matching elements in list in Python

我有一長串從 1 到 5 的浮點數,稱為“平均值”,我想返回小於 a 或大於 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)

但令人驚訝的是,“matches”的輸出中有很多重復,例如[2, 2, 10, 2, 2, 2, 19, 2, 10, 2, 2, 42, 2, 2, 10, 2, 2, 2, 10, 2, 2, ...]

為什么會這樣?

您正在使用.index() ,它只會在列表中找到您的值的第一次出現。 因此,如果您在索引 2 和索引 9 處有一個值 1.0,那么.index(1.0)始終返回2 ,無論1.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

您可以將其折疊為列表理解:

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

如果你做了很多這類事情,你應該考慮使用numpy

In [56]: import random, numpy

In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list

In [58]: a, b = 1, 3

In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])

針對Seanny123的問題,我使用了這個時序代碼:

import numpy, timeit, random

a, b = 1, 3

lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])

def numpy_way():
    numpy.flatnonzero((lst > 1) & (lst < 3))[:10]

def list_comprehension():
    [e for e in lst if 1 < e < 3][:10]

print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)

numpy 版本快了 60 多倍。

>>> average =  [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM