Alphabetical pairing of CSV elements while keeping first element constant in python
<p>How is it possible to take a CSV file with rows of varying lengths (up to 12 in practice) as input and then output a new CSV file where new rows consist of 
the 0th element of each row + each unique pair of elements (>0th) in alphabetical order?</p>

<p>The original row elements are not in alphabetical order.</p>

<p>Please see image for example input and output.
<a href="http://i.stack.imgur.com/tbQgo.jpg" rel="nofollow">enter image description here</a></p>

<p>You can use <a href="https://docs.python.org/3/library/csv.html#module-csv" rel="nofollow"><code>csv</code></a> for reading &amp; writing and <a href="https://docs.python.org/3.5/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations</code></a> for generating the pairs:</p>

<pre><code>import csv
from itertools import combinations

with open('input.csv') as in_f, open('output.csv', 'w') as out_f:
    reader = csv.reader(in_f)
    writer = csv.writer(out_f)

    for row in reader:
        for combination in combinations(sorted(row[1:]), 2):
            writer.writerow(tuple(row[:1]) + combination)
</code></pre>

<p>Output:</p>

<pre><code>0,A,B
1,A,B
1,A,C
1,B,C
2,A,B
2,A,C
2,A,D
2,B,C
2,B,D
2,C,D
</code></pre>

python python-3.x sorting csv itertools