简体   繁体   English

查找集合列表的组合

[英]Find combinations of a list of sets

I'm using python 2.7.我正在使用 python 2.7。 Given a list of sets, is there any quick and efficient way to generate the combinations?给定一组集合,是否有任何快速有效的方法来生成组合? Input sets always have one item in each set and output sets all have length of 2输入集在每个集中总是有一个项目,输出集的长度都是 2

From:从:

[set(['item1']), set(['item2']), set(['item3'])]

To:到:

[set(['item1','item2']), set(['item2','item3']), set(['item3','item1'])]

Since the elements in your list of sets are all 1-element sets, the combinations that you are looking for are just the 2-element subsets of the union of those sets.由于集合列表中的元素都是 1 元素集合,因此您要查找的组合只是这些集合的并集的 2 元素子集。 You can obtain them like this:您可以像这样获取它们:

>>> import itertools

>>> sets = [set(['item1']), set(['item2']), set(['item3'])]
>>> elements = set()
>>> for s in sets: elements.update(s)

thus因此

>>> elements
{'item1', 'item2', 'item3'}

And then, just this:然后,就这样:

>>> pairs = [set(combo) for combo in itertools.combinations(elements,2)]
>>> pairs
[{'item1', 'item2'}, {'item1', 'item3'}, {'item2', 'item3'}]

As John pointed out itertools might be of help.正如约翰指出的那样itertools可能会有所帮助。 Here's a quick example:这是一个快速示例:

import itertools as it
sets = [set(range(0, 3)), set(range(2, 5)), set(range(4, 7))]
comb = list(it.combinations(sets, r=2))
comb

output: [({0, 1, 2}, {2, 3, 4}), ({0, 1, 2}, {4, 5, 6}), ({2, 3, 4}, {4, 5, 6})]输出: [({0, 1, 2}, {2, 3, 4}), ({0, 1, 2}, {4, 5, 6}), ({2, 3, 4}, {4, 5, 6})]

Then create an intersection in each iteration:然后在每次迭代中创建一个交集:

comb_sets = [a.intersection(b) for a, b in comb]
comb_sets

output: [{2}, set(), {4}]输出: [{2}, set(), {4}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM