2

我有一个清单

a = [1.0, 1.2, 1.1, 1.4, 0.1]

并从该列表中我想获得满足某些标准的第一个值的索引,例如x > 1.1

在 python 中这样做的好方法是什么?

4

3 回答 3

5

您可以结合nextenumerate

>>> next(i for i,x in enumerate(a) if x > 1.1)
1
>>> next(i for i,x in enumerate(a) if x > 1.3)
3

或者

>>> next((i,x) for i,x in enumerate(a) if x > 1.3)
(3, 1.4)

如果你想要两者。

于 2013-01-29T11:46:16.467 回答
0

你可以这样做:

def analyze(l, criteria):
    for idx in range(len(l)):
        if criteria(l[idx]):
            return idx

然后像这样使用它:

a = [1.0, 1.2, 1.1, 1.4, 0.1]
analyze(a, lambda x: x > 1.1)

我不认为它太pythonic。可能有更多的pythonic方式。

于 2013-01-29T11:45:09.093 回答
0

我认为这可能比其他一些答案更具pythonic - 如果这就是你所追求的。

a = [1.0, 1.2, 1.1, 1.4, 0.1]

def crit(x):
    return x > 1.3

index = None
for i,v in enumerate(a):
    if crit(v):
        index = i
        break

print index
于 2013-01-29T11:53:58.803 回答