【发布时间】:2026-02-11 21:15:01
【问题描述】:
如果我有一个函数 matchCondition(x),如何删除 Python 列表中符合该条件的第一个 n 项?
一种解决方案是遍历每个项目,将其标记为删除(例如,将其设置为None),然后使用推导式过滤列表。这需要对列表进行两次迭代并改变数据。有没有更惯用或更有效的方法来做到这一点?
n = 3
def condition(x):
return x < 5
data = [1, 10, 2, 9, 3, 8, 4, 7]
out = do_remove(data, n, condition)
print(out) # [10, 9, 8, 4, 7] (1, 2, and 3 are removed, 4 remains)
【问题讨论】:
标签: python list list-comprehension