Find combinations of a list of sets
<p>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 <br><br>
From:</p>

<pre><code>[set(['item1']), set(['item2']), set(['item3'])]
</code></pre>

<p>To:</p>

<pre><code>[set(['item1','item2']), set(['item2','item3']), set(['item3','item1'])]
</code></pre>

<p>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:</p>

<pre><code>&gt;&gt;&gt; import itertools

&gt;&gt;&gt; sets = [set(['item1']), set(['item2']), set(['item3'])]
&gt;&gt;&gt; elements = set()
&gt;&gt;&gt; for s in sets: elements.update(s)
</code></pre>

<p>thus</p>

<pre><code>&gt;&gt;&gt; elements
{'item1', 'item2', 'item3'}
</code></pre>

<p>And then, just this:</p>

<pre><code>&gt;&gt;&gt; pairs = [set(combo) for combo in itertools.combinations(elements,2)]
&gt;&gt;&gt; pairs
[{'item1', 'item2'}, {'item1', 'item3'}, {'item2', 'item3'}]
</code></pre>

python python-2.7 set combinations