![](/img/trans.png)
[英]Get the list of names which satisfy the condition in dictionary from given list
[英]Python - get index of list from which on all further entries satisfy condition
想象一下我有一个清单
l = [12,13,14,10,13,14]
我想找到所有项目都大于10
的索引(在这种情况下,它是对应于13
的索引4
作为该属性的第一次出现)。
也许基于此,如何用 Python 做到最好?
我的想法:为此[a>10 for a in l]
创建一个布尔列表(由True
和False
作为序列组成),或者l>10
以某种方式使用numpy
产生一个数组?
您可以向后迭代列表并捕获第一个条件失败的索引。 这可以防止多个值失败的问题......
In [51]: l
Out[51]: [12, 13, 14, 10, 13, 14]
In [52]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)
Out[52]: 4
In [53]: l = [12, 13, 10, 20, 10, 15]
In [54]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)
Out[54]: 5
In [55]: l = [23, 55]
In [56]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)
In [57]:
l = [12,13,14,10,13,14]
i = len(l)
for i in reversed(l):
condition = v > 10
if not condition:
break
i -= 1
print(i)
# Output : 4
小心列表的最后一个元素不满足条件的情况。 i 值将等于 len(l) ,这不是列表的有效索引。 您可以选择如何管理该特殊情况。
您可以从数组的末尾开始:
def findStartOfMoreThan(l,limit):
for i in range(len(l)-1, -1, -1):
if l[i]<=limit :
return i+1
return (-1)
assert(findStartOfMoreThan([12,13,14,10,13,14],10) == 4)
assert(findStartOfMoreThan([12,13,14,10,13,14,15],10)==4)
assert(findStartOfMoreThan([0,12,13,14,10,13,14,15],10)==5)
assert(findStartOfMoreThan([0,12,13,14,10,13,14,15],13)==6)
最简单的解决方案是否定条件以获取具有element <=10
的最后一个索引,使用
l = np.array([12,13,14,10,13,14])
first_index = np.where(l<=10)[0][-1]+1 # yields the first index that satisfies the condition
可以首先检查len(np.where(...))
以验证是否违反了至少一次条件,否则为第一个索引返回 0。
这里是 go:
[l.index(item) for item in l if not item>10][-1]+1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.