如何根据python中的另一个列表/集过滤列表列表.对于一个简单的列表,可以这样做:
mylist = [1,2,3,4,5,3,5,2,3,2,7,5,3] [x for x in mylist if x in {3,5}]
但是如何最有效地为列表列表执行此操作:
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])
结果应该仍然是以下列表:
[[], [], [], [4], [10], [4, 10]]
Eugene Yarma.. 5
基本上,同样的想法:
>>> 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
是常量,则可以使用列表推导中的set literal替换它以获得更好的性能.
基本上,同样的想法:
>>> 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
是常量,则可以使用列表推导中的set literal替换它以获得更好的性能.