在列表中第一个传递条件的元素之后添加一个元素

add an element after the first element which passes a condition in a list

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):

您可以为您的条件使用迭代器 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]
备选

您的代码的 one-liner 等效项(在不匹配的情况下具有相同的缺陷)可以使用 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]