用另一个列表过滤列表的Python列表 [英] Filter Python list of lists by another list

查看:109
本文介绍了用另一个列表过滤列表的Python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何基于python中的另一个列表/集合过滤列表列表. 对于一个简单的列表,可以通过以下方式完成:

How can I filter a list of lists based on another list/set in python. For a simple list this can be done as:

mylist = [1,2,3,4,5,3,5,2,3,2,7,5,3]
[x for x in mylist if x in {3,5}]

但是如何最有效地执行列表操作:

But how to do that for a list of lists most efficiently:

mylistoflists = [[], [5, 1, 6], [5, 1, 6, 2, 7], [5, 1, 6, 2, 7, 4, 8], [5, 1, 11, 10], [5, 1, 4, 11, 10, 12]]
myvalues = set([4,10])

结果仍然应该是如下列表的列表:

The results should still be a list of lists like following:

 [[], [], [], [4], [10], [4, 10]]

推荐答案

基本上,相同的想法:

>>> mylistoflists = [[], [5, 1, 6], [5, 1, 6, 2, 7], [5, 1, 6, 2, 7, 4, 8], [5, 1, 11, 10], [5, 1, 4, 11, 10, 12]]
>>> myvalues = {4, 10}
>>> [[x for x in L if x in myvalues] for L in mylistoflists]
[[], [], [], [4], [10], [4, 10]]

如果myvalues是常量,则可以在列表理解中将其替换为设置的文字,以获得更好的性能.

If myvalues is a constant, you can replace it with a set literal in the list comprehension for better performance.

这篇关于用另一个列表过滤列表的Python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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