我有一个包含数字的列表(子列表)列表,我只想保留所有(子)列表中存在的列表。在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