Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove duplicate tuples from a list based on index value of tuple while maintaining the order of tuple? [duplicate]

I want to remove those tuples which had same values at index 0 except the first occurance. I looked at other similar questions but did not get a particular answer I am looking for. Can somebody please help me? Below is what I tried.

from itertools import groupby
import random
Newlist = []

abc = [(1,2,3), (2,3,4), (1,0,3),(0,2,0), (2,4,5),(5,4,3), (0,4,1)]

Newlist = [random.choice(tuple(g)) for _, g in groupby(abc, key=lambda x: x[0])]
print Newlist

my expected output : [(1,2,3), (2,3,4), (0,2,0), (5,4,3)]

like image 647
A.S Avatar asked Apr 17 '18 14:04

A.S


1 Answers

A simple way is to loop over the list and keep track of which elements you've already found:

abc = [(1,2,3), (2,3,4), (1,0,3),(0,2,0), (2,4,5),(5,4,3), (0,4,1)]
found = set()
NewList = []
for a in abc:
    if a[0] not in found:
        NewList.append(a)
    found.add(a[0])
print(NewList)
#[(1, 2, 3), (2, 3, 4), (0, 2, 0), (5, 4, 3)]

found is a set. At each iteration we check if the first element in the tuple is already in found. If not, we append the whole tuple to NewList. At the end of each iteration we add the first element of the tuple to found.

like image 145
pault Avatar answered Sep 25 '22 19:09

pault