Home > other >  How to remove duplicate who are followed each other in a list
How to remove duplicate who are followed each other in a list

Time:12-07

In a list I need to delete duplicate that follow each other in a list like in this example:

[("0", "1"), ("1", "2"), ("0", "2"), ("2", "0")]

and the output I want:

["0", "1", "2", "0", "2", "0"]

I tried nothing because I have no idea what to do, maybe iterate over the list and use if index[0] == index[1].

CodePudding user response:

Use a simple nested loop tracking the previous element:

l = [('0', '1'), ('1', '2'), ('0', '2'), ('2', '0')]

out = []
prev = None
for t in l:
    for x in t:
        if x != prev:
            out.append(x)
        prev = x
print(out)

Output: ['0', '1', '2', '0', '2', '0']

If you really want a list with a single tuple:

out = [tuple(out)]

Output: [('0', '1', '2', '0', '2', '0')]

CodePudding user response:

you need to flatten your list first (i do that with chain(*lst)) and then you could use groupby in order to skip consecutive duplicates:

from itertools import chain, groupby

lst = [('0', '1'), ('1', '2'), ('0', '2'), ('2', '0')]
ret = tuple(item for item, _ in groupby(chain(*lst)))

print(ret)
# ('0', '1', '2', '0', '2', '0')

you may of course wrap that in a list - if that is really the data structure you need.

CodePudding user response:

You can do this in several successive steps (which could actually be merged):

tuplist = [('0', '1'), ('1', '2'), ('0', '2'), ('2', '0')]

# unpacking tuples
list2 = []
for t in tuplist:
    list2.extend(t) #shorter way of doing list2  = [t[0], t[1]]
    
# removing duplicates
list3 = [list2[0]]
for i in list2[1:]:
    if i != list3[-1]:
        list3.append(i)
        
# converting list3 to the desired format
list4 = [tuple(list3)]
  • Related