我想在Python(2.7)中交叉兩個列表。我需要的結果是迭代:Python列表交集效率:generator還是filter()?
list1 = [1,2,3,4]
list2 = [3,4,5,6]
result = (3,4) # any kind of iterable
提供完整的迭代將要執行的第一件事交集之後,下列哪項是更有效率?
使用發電機:
result = (x for x in list1 if x in list2)
使用過濾器():
result = filter(lambda x: x in list2, list1)
其他建議?
由於提前,
阿姆農
有趣的是,'set(list1)。相交(列表2)'比'set(list1)&set(列表2)'更快,我猜這是因爲創建兩個集合比加載和調用'.intersection()'hmm更加昂貴.. – mouad 2011-06-16 09:32:42
@mouad在我的機器,'set(list1)&set(list2)'比使用'.intersection()'快。但差異不是很顯着。 – pemistahl 2013-02-16 17:50:41
這是否需要列表進行排序? – Youda008 2016-11-15 09:51:43