for i,k in enumerate(ls):
if k == 3:
ls.insert(i 1,"example")
break
上面的代碼遍歷一個串列ls并找到第一個等于 3 的元素并插入"example"到該元素之后并停止。雖然上面的代碼可以寫成,
ls.insert(ls.index(3) 1,"example")
撰寫程式以在通過條件的第一個元素之后輸入元素的最有效方法是什么,例如,
if k > 3:
或者
if isPrime(k):
uj5u.com熱心網友回復:
您可以為您的條件使用迭代器,并且next:
ls = list(range(10))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
idx = next((i for i in range(len(ls)) if ls[i]>3), # could be isPrime(ls[i])
len(ls)) # default insertion in the end
ls.insert(idx 1, 'X')
# [0, 1, 2, 3, 4, 'X', 5, 6, 7, 8, 9]
如果不滿足條件不想插入:
idx = next((i for i in range(len(ls)) if ls[i]>10), None)
if idx is not None:
ls.insert(idx 1, 'X')
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
選擇
您的代碼的單行等效項(在不匹配的情況下具有相同的缺陷)可以使用itertools.dropwhile(注意反轉條件):
ls = list(range(10))
from itertools import dropwhile
ls.insert(ls.index(next(dropwhile(lambda x: not x>3, ls))) 1, 'X')
輸出:[0, 1, 2, 3, 4, 'X', 5, 6, 7, 8, 9]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/459270.html
