我有一個包含數字的列表(子列表)列表,我只想保留所有(子)列表中存在的列表。在Python中查找(並保留)子列表的副本
例子:
x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]
output => [3, 4]
我怎樣才能做到這一點?
我有一個包含數字的列表(子列表)列表,我只想保留所有(子)列表中存在的列表。在Python中查找(並保留)子列表的副本
例子:
x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]
output => [3, 4]
我怎樣才能做到這一點?
common = set(x[0])
for l in x[1:]:
common &= set(l)
print list(common)
或:
import operator
print reduce(operator.iand, map(set, x))
在一個班輪:
>>> reduce(set.intersection, x[1:], set(x[0]))
set([3, 4])
或者列表(reduce(set.intersection,x [1:],set(x [0]))) – grokus 2009-11-12 16:12:59
def f(a, b):
return list(set(a).intersection(set(b)))
reduce(f, x)
解決,如納迪亞但不使用降低幾乎相同的另一種方式,我用地圖:
>>> x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]
>>> set.intersection(*map(set,x))
set([3, 4])
>>>
我最初是用set()開始的,現在已經修復了。 – 2009-11-12 15:38:26
是的,我發佈了一個修改你的工作的答案,但到了我回來的時候你就編輯了它。可悲的是,stackoverflow不會讓我+1你,因爲我upvoted,然後解開我upvote。雖然很好的答案! – 2009-11-12 15:40:01