Delete unique elements from a list

前端 未结 9 1229
[愿得一人]
[愿得一人] 2020-12-10 09:20

I faced some problem with solving the next problem:

We have a list of elements (integers), and we should return a list consisting of only the non-unique elements in

9条回答
  •  轮回少年
    2020-12-10 10:10

    You can implement a OrderedCounter, eg:

    from collections import OrderedDict, Counter
    
    class OrderedCounter(Counter, OrderedDict): 
        pass
    
    data = [1, 3, 1, 2, 3, 5, 8, 1, 5, 2]
    
    duplicates = [k for k, v in OrderedCounter(data).items() if v > 1]
    # [1, 3, 2, 5]
    

    So you count the occurrence of each value, then filter on if it has a frequency of more than one. Inheriting from OrderedDict means the order of the original elements is preserved.


    Going by comments, you want all duplicated elements reserved, so you can pre-build a set of the duplicate entries, then re-iterate your original list, eg:

    from collections import Counter
    
    data = [1, 3, 1, 2, 3, 5, 8, 1, 5, 2]
    duplicates = {k for k, v in Counter(data).items() if v > 1}
    result = [el for el in data if el in duplicates]
    # [1, 3, 1, 2, 3, 5, 1, 5, 2]
    

提交回复
热议问题