Rya Rya - 2 months ago 11
Python Question

Merge elements in tuples?

Here I have a dataset:

rd='''
1:A,B,C;D,E
2:F,G
3:H,J,K
'''


Desired result:

[('A','B'),('B',C'),('A','C'),('D','E'),('F','G'),('H','J'),('J','K'),('H','K')]


My 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 <j
j +=1
if j >len(edge):
end
i +=1
if i >len(edge)-1:
end
allEdges.append(edge(i),edge(j))

return allEdges

print rd_edges(rd)


I know the
itertools
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.

Answer

Here is how you could do it without import of itertools:

def rd_edges(f):
    allEdges =[]
    for line in f.split():
        edges = line.split(":")[1].split(';')
        for edge in edges:
            nodes = edge.split(',')
            for i, a in enumerate(nodes):
                for b in nodes[i+1:]:
                    allEdges.append((a,b))
    return allEdges

rd='''
1:A,B,C;D,E
2:F,G
3:H,J,K
'''
print (rd_edges(rd))