How do I find the duplicates in a list and create another list with them?

前端 未结 30 2225
梦谈多话
梦谈多话 2020-11-22 00:56

How can I find the duplicates in a Python list and create another list of the duplicates? The list only contains integers.

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 01:12

    Here's a fast generator that uses a dict to store each element as a key with a boolean value for checking if the duplicate item has already been yielded.

    For lists with all elements that are hashable types:

    def gen_dupes(array):
        unique = {}
        for value in array:
            if value in unique and unique[value]:
                unique[value] = False
                yield value
            else:
                unique[value] = True
    
    array = [1, 2, 2, 3, 4, 1, 5, 2, 6, 6]
    print(list(gen_dupes(array)))
    # => [2, 1, 6]
    

    For lists that might contain lists:

    def gen_dupes(array):
        unique = {}
        for value in array:
            is_list = False
            if type(value) is list:
                value = tuple(value)
                is_list = True
    
            if value in unique and unique[value]:
                unique[value] = False
                if is_list:
                    value = list(value)
    
                yield value
            else:
                unique[value] = True
    
    array = [1, 2, 2, [1, 2], 3, 4, [1, 2], 5, 2, 6, 6]
    print(list(gen_dupes(array)))
    # => [2, [1, 2], 6]
    

提交回复
热议问题