Assume I have list of tuples a=[(0,1),(2,0),(1,4)]
and I want to return unique element of each two tuples as a new tuple. For example (0,1)
and (2,0)
returns(1,2)
. Also (0,1)
and (1,4)
return (0,4)
.
Therefore, output is unique=[(1,2),(0,4)]
I tried code below but it seems I am not in correct path:
from itertools import combinations
a=[(0,1),(2,0),(1,4)]
b=list(combinations(a,2))
def myComp(pair1, pair2):
if any(x == y for x, y in zip(pair1, pair2)):
return(pair1,pair2)
d=[]
for i in range(len(b)):
c=myComp(b[i][0],b[i][1])
d.append(c)
crude answer without any list comps:
from itertools import combinations
a = [(0,1),(0,2),(0,3),(1,2),(1,3),(1,4),(2,3)]
uniques = []
for x, y in combinations(a,2):
z = []
for i in x:
if i not in y:
z.append(i)
for i in y:
if i not in x:
z.append(i)
if len(z) == 2:
uniques.append(tuple(z))
print(list(set(uniques)))
[(0, 1), (2, 4), (1, 2), (0, 4), (3, 4), (0, 3), (2, 3), (0, 2), (1, 3)]