Home > Blockchain >  How can I select a specific number in a list with duplicates without removing the previous same valu
How can I select a specific number in a list with duplicates without removing the previous same valu

Time:11-26

I have the following list in python3:

a = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3]

I want to have something like this as an output:

b = [1, 2, 3, 1, 2, 4, 3]

How can I do that? I have tried a = set(a) and other methods for getting rid of duplicates. But they remove all duplicates.

CodePudding user response:

If you are willing to use a module, you can use itertools.groupby:

from itertools import groupby

a = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3]

output = [k for k, _ in groupby(a)]
print(output) # [1, 2, 3, 1, 2, 4, 3]

CodePudding user response:

This would work:

a = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3]
b = [a[0]]
for k in a:
    if k!=b[-1]:
        b.append(k)
print(b)
  • Related