# Python3 program for intersection() function
set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {4,6,8}
# union of two sets
print("set1 intersection set2 : ", set1.intersection(set2))
# union of three sets
print("set1 intersection set2 intersection set3 :", set1.intersection(set2,set3))
from itertools import combinations
for comboSize in range(2,len(sets)):
for combo in combinations(range(len(sets)),comboSize):
intersection = sets[combo[0]]
for i in combo[1:]: intersection = intersection & sets[i]
print(" and ".join(f"Set{i+1}" for i in combo),"=",intersection)
Set1 and Set2 = {4, 5}
Set1 and Set3 = set()
Set1 and Set4 = {1}
Set2 and Set3 = {6, 7}
Set2 and Set4 = set()
Set3 and Set4 = {8, 9}
Set1 and Set2 = {4, 5}
Set1 and Set3 = set()
Set1 and Set4 = {1}
Set2 and Set3 = {6, 7}
Set2 and Set4 = set()
Set3 and Set4 = {8, 9}
Set1 and Set2 and Set3 = set()
Set1 and Set2 and Set4 = set()
Set1 and Set3 and Set4 = set()
Set2 and Set3 and Set4 = set()
你需要找到2组组合(从你想要的输出中扣除)。这可以通过使用[Python 3.Docs]: itertools.combinations(iterable, r)来实现。对于每个组合,应执行两组之间的相交。
为了完成上述操作,(输入)集合被“分组”在一个列表(iterable)中。你知道吗
同时指出[Python 3.docs]: classset([iterable])。你知道吗
代码.py:
请注意,[Python 3.Docs]: Built-in Functions - enumerate(iterable, start=0)仅用于打印目的(Set1,Set2。。。在输出中)。你知道吗
输出:
从here:
从docs开始:
如果只查找两个集合的交集,只需执行嵌套for循环:
如果要查找任意数量的这些集合的交集,则可以使用itertools中的combinations()生成索引的幂集,并对每个组合执行交集:
相关问题 更多 >
编程相关推荐