Keep duplicates in a list in Python

后端 未结 4 1974
悲哀的现实
悲哀的现实 2021-01-12 01:00

I know this is probably an easy answer but I can\'t figure it out. What is the best way in Python to keep the duplicates in a list:

x = [1,2,2,2,3,4,5,6,6,7         


        
相关标签:
4条回答
  • 2021-01-12 01:06

    keepin' it simple:

    array2 = []
    aux = 0
    aux2=0
    for i in x:
        aux2 = i
        if(aux2==aux):
            array2.append(i)
        aux= i
    list(set(array2))
    

    That should work

    0 讨论(0)
  • 2021-01-12 01:06

    Not efficient but just to get the output, you could try:

    import numpy as np
    
    def check_for_repeat(check_list):
        repeated_list = []
    
        for idx in range(len(check_list)):
            elem = check_list[idx]
            check_list[idx] = None
    
            if elem in temp_list:
                repeated_list.append(elem)
    
        repeated_list = np.array(repeated_list)
    
        return list(np.unique(repeated_list))
    
    0 讨论(0)
  • 2021-01-12 01:15

    This is a short way to do it if the list is sorted already:

    x = [1,2,2,2,3,4,5,6,6,7]
    
    from itertools import groupby
    print [key for key,group in groupby(x) if len(list(group)) > 1]
    
    0 讨论(0)
  • 2021-01-12 01:29

    I'd use a collections.Counter:

    from collections import Counter
    x = [1, 2, 2, 2, 3, 4, 5, 6, 6, 7]
    counts = Counter(x)
    output = [value for value, count in counts.items() if count > 1]
    

    Here's another version which keeps the order of when the item was first duplicated that only assumes that the sequence passed in contains hashable items and it will work back to when set or yeild was introduced to the language (whenever that was).

    def keep_dupes(iterable):
        seen = set()
        dupes = set()
        for x in iterable:
            if x in seen and x not in dupes:
                yield x
                dupes.add(x)
            else:
                seen.add(x)
    
    print list(keep_dupes([1,2,2,2,3,4,5,6,6,7]))
    
    0 讨论(0)
提交回复
热议问题