【问题标题】:How to create every possible pairs of sets?如何创建所有可能的集合对?
【发布时间】:2020-12-17 21:32:59
【问题描述】:

我有两个包含 n 个元素的列表,每个列表在两个集合之间没有公共元素:

SetA= [a1, a2 ... an]

SetB= [b1, b2 ... bn]

我想生成每对可能的列表 SetXSetY 使得 SetX 有一半来自 SetA 的元素和一半来自 SetB 的元素,而SetY 有剩余的元素来自SetASetB

Python 有没有办法做到这一点?

【问题讨论】:

  • 您应该可以使用itertools 执行此操作。
  • 是的,有办法做到这一点,但请添加更多详细信息、输入、预期输出。你试过什么。

标签: python set combinations permutation


【解决方案1】:

刚刚查看了@Barmar 的评论并想出了这个解决方案:

import itertools

s1= [1, 2, 3, 4, 5, 6]
s2= ['a', 'b', 'c', 'd', 'e', 'f']
u= s1 + s2
n= len(s1)

total= 0
for subs1 in itertools.combinations(s1, int(n/2)):
    for subs2 in itertools.combinations(s2, int(n/2)):
        total= total + 1
        x= list(subs1)
        x.extend(list(subs2))
        y= list(set(u) - set(x))
        print(x)
        print(y)
        print('--------')
print(total)

【讨论】:

    猜你喜欢
    • 2018-06-08
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    相关资源
    最近更新 更多