ysj ysj - 11 months ago 66
Python Question

Find combinations of a list of sets

I'm using 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


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


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

Answer Source

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. You can obtain them like this:

>>> import itertools

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


>>> 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'}]