Remove duplicate characters from Python3 (remove consecutive cases only)

Asked 2 years ago, Updated 2 years ago, 109 views

ex) [3,5,7,7,3,7,3,3,5] For the list

The set returns the result to {3,5,7}.

The return price I want is [3,5,7,3,7,3,5] This is a case that you want to remove only if the same character or number comes next.

I would like to ask if there is a simple function.

python duplicate-elimination

2022-09-22 11:46

2 Answers

I didn't have a library that I know, so I made it as a function.

def list_overlap_del(input_list):
    result_list = []

    for i in range(len(input_list)):
        if i == 0:
            list_temp.append(input_list[i])                        
        elif list_temp[-1] != input_list[i]:
            list_temp.append(input_list[i])           
    return result_list


2022-09-22 11:46

It can be expressed simply using groupby, but I don't think it's an efficient method.

>>> import itertools
>>> L = [3,5,7,7,3,3,7,3,5]
>>> G = itertools.groupby(L)
>>> [k for k, v in G]
[3, 5, 7, 3, 7, 3, 5]


2022-09-22 11:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.