删除与Python列表中的条件匹配的前N个项目 [英] Remove the first N items that match a condition in a Python list

查看:149
本文介绍了删除与Python列表中的条件匹配的前N个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我具有函数matchCondition(x),如何删除与该条件匹配的Python列表中的前n个项目?

If I have a function matchCondition(x), how can I remove the first n items in a Python list that match that condition?

一种解决方案是遍历每个项目,将其标记为删除(例如,将其设置为None),然后使用理解过滤列表.这需要遍历列表两次,并对数据进行突变.有没有更惯用或有效的方法来做到这一点?

One solution is to iterate over each item, mark it for deletion (e.g., by setting it to None), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the data. Is there a more idiomatic or efficient way to do this?

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)

推荐答案

使用 itertools.count :

from itertools import count, filterfalse

data = [1, 10, 2, 9, 3, 8, 4, 7]
output = filterfalse(lambda L, c=count(): L < 5 and next(c) < 3, data)

然后list(output),给您:

[10, 9, 8, 4, 7]

这篇关于删除与Python列表中的条件匹配的前N个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆