我有一个集合列表:
setlist = [s1,s2,s3...]
我想要s1 s2 s3∩∩...
我可以编写一个函数,通过执行一系列成对的s1.intersection(s2)
等来完成这项工作。
有没有推荐的、更好的或者内置的方法?
发布于 2010-03-30 06:58:50
在2.6版本中,set.intersection
可以接受任意多个可迭代变量。
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s3 = set([2, 4, 6])
>>> s1 & s2 & s3
set([2])
>>> s1.intersection(s2, s3)
set([2])
>>> sets = [s1, s2, s3]
>>> set.intersection(*sets)
set([2])
发布于 2012-02-29 09:18:36
显然,在这里set.intersection
是您想要的,但是如果您需要“取所有这些的和”、“取所有这些的乘积”、“取所有这些的xor”的泛化,那么您需要的是reduce
函数:
from operator import and_
from functools import reduce
print(reduce(and_, [{1,2,3},{2,3,4},{3,4,5}])) # = {3}
或
print(reduce((lambda x,y: x&y), [{1,2,3},{2,3,4},{3,4,5}])) # = {3}
发布于 2010-04-01 06:50:38
在这里,我提供了一个多集合交集的通用函数,试图利用可用的最佳方法:
def multiple_set_intersection(*sets):
"""Return multiple set intersection."""
try:
return set.intersection(*sets)
except TypeError: # this is Python < 2.6 or no arguments
pass
try: a_set= sets[0]
except IndexError: # no arguments
return set() # return empty set
return reduce(a_set.intersection, sets[1:])
Guido可能不喜欢reduce
,但我有点喜欢它:)
https://stackoverflow.com/questions/2541752
复制相似问题