![](/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.