Merge elements in tuples?
<p>Here I have a dataset:</p>

<pre><code>rd='''
1:A,B,C;D,E
2:F,G
3:H,J,K
'''
</code></pre>

<p>Desired result:</p>

<pre><code>[('A','B'),('B',C'),('A','C'),('D','E'),('F','G'),('H','J'),('J','K'),('H','K')]
</code></pre>

<p>My code:</p>

<pre><code>def rd_edges(f):
    allEdges =[]
    for line in f.split():
        edges =line.split(":")[1].split(';')
        for edge in edges:
            i =0
            j =1
            for i in len(edge):
                for j in len(edge):
                    i &lt;j
                    j +=1
                    if j &gt;len(edge):
                        end
                i +=1
                if i &gt;len(edge)-1:
                    end
            allEdges.append(edge(i),edge(j))       

    return allEdges
</code></pre>

<p>I know the <code>itertools</code> module can solve this problem, but want to write a function to transfer the data into a tuple without importing any modules. I reviewed some past questions posted on the forum, but am still confused about doing this.</p>

<p>Below is the simplified solution to achieve it using <a href="https://docs.python.org/2/library/re.html#re.compile" rel="nofollow"><code>re.compile()</code></a> and <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations()</code></a> functions. In order to flatten the list, I am using <a href="https://docs.python.org/2/library/operator.html#operator.add" rel="nofollow"><code>operator.add()</code></a> with <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow"><code>reduce()</code></a> function:</p>

<pre><code>import re
from itertools import combinations
from operator import add
rd='''
1:A,B,C;D,E
2:F,G
3:H,J,K
'''
my_aplhalist = (re.compile('(\n\d:)').split(rd.rstrip()))[2::2]
my_combinations = [list(combinations(item.split(','), 2)) for item_str in my_aplhalist for item in item_str.split(';')]
my_solution = reduce(add, my_combinations)
# Value of 'my_solution': [('A', 'B'), ('A', 'C'), ('B', 'C'), ('D', 'E'), ('F', 'G'), ('H', 'J'), ('H', 'K'), ('J', 'K')]
</code></pre>

python tuples