Skip to content Skip to sidebar Skip to footer

How To Delete Repeat Elements In This List?

I have a list is a = ['R','R','R','B','R','B','B','S','S']. my goal is to delete repeat 'R's and 'S's and then delete the 'B's (if there is only one R or S, just keep it). Therefor

Solution 1:

You could use itertools.groupby to group the elements first, then delete the B values:

from itertools import groupby

a = ['R','R','R','B','R','B','S','S']  # create a list to store R S B
[k for k, v in groupby(a) if k != 'B']

Result:

['R', 'R', 'S']

Solution 2:

You can use fromkeys in this case.

mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist) # ['a', 'b', 'c']

Post a Comment for "How To Delete Repeat Elements In This List?"