问题描述
我正在尝试获取每个成员仅出现一次的排列/组合组(r = 2)
I'm trying to get groups of permutations/combinations (r=2) that each member appear only once
我使用python'combinations'软件包进行组合.
I used python 'combinations' package to have the combinations.
例如:成员是: a,b,c,d.组合为: [a,b],[a,c],[a,d],[b,c],[b,d] ...
For example: the members are: a,b,c,d.The combinations are: [a,b],[a,c],[a,d],[b,c],[b,d]...
我想要的输出是: [{[a,b],[c,d]},{[a,c],[b,d]},{[a,d],[b,c]} ...]
我想知道这种情况的用语,以及是否已经实现了该用语.
I would like to know what is the terminology for that case and if there is already implementation for that.
谢谢.
推荐答案
这是一种实现方法:
from itertools import combinations, chain
l = ['a','b','c','d']
c = list(combinations(l,2))
[set(i) for i in list(combinations(c,2)) if (len(set(l) & set(chain(*i))) == len(l))]
[{('a', 'b'), ('c', 'd')}, {('a', 'c'), ('b', 'd')}, {('a', 'd'), ('b', 'c')}]
说明
您可以在其中两次使用 itertools.combinations
以便从以下位置获取所有2个元组组合:
You can use itertools.combinations
twice, in order to get all the 2 tuple combinations from:
list(combinations(l,2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
并仅选择元素集与原始列表的元素相交的元素(len(set(l) & set(chain(*i))) == len(l))
)用于每种可能的组合.
And select only those whose set of elements intersect with that of the original list, len(set(l) & set(chain(*i))) == len(l))
for every possible combination.
这篇关于python获取每个成员仅出现一次的组合组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!