要从列表中删除项目? [英] To remove items from a list?
本文介绍了要从列表中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试删除列表中的项目,如果这些项目不存在于另一个列表中,但我的程序无法正常运行
例如:
i am trying to remove items in a list if the items do not exist in another list but my program does not work the way i have expected
for example:
展开 | 选择 | Wrap | 行号
推荐答案
棘手的问题:)
尝试了一会儿在放弃之前我虽然使用了2个相同的列表。
Tricky problem :)
After trying a while, before giving up I though about using 2 identical lists.
展开 | 选择 | Wrap | 行号
不喜欢过滤器?你毕竟是过滤了;)
两种可能性:
x = [要过滤的列表]
y = [要过滤的术语列表]
过滤器(lambda x:x不在y,x)
或
[如果p不在y,则p为p in x]
et voila。
list comp is可能更快(我还没有测试过)
no love for filter? you are filtering after all ;)
two possibilities:
x =[list to be filtered]
y =[list of terms to be filtered out]
filter(lambda x: x not in y,x)
or
[p for p in x if p not in y]
et voila.
list comp is probably faster (i haven''t tested)
非常好的benjumanji。 filter()解决方案很好,但由于速度和可读性,我更喜欢列表理解。使用 timeit()进行测试时,列表理解速度提高了两倍。
Very good benjumanji. The filter() solution is fine, but I prefer the list comprehension due to its speed and readability. The list comprehension was twice as fast when tested with timeit().
这篇关于要从列表中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文