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

前端 未结 30 1585
梦谈多话
梦谈多话 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:20

    There are a lot of answers up here, but I think this is relatively a very readable and easy to understand approach:

    def get_duplicates(sorted_list):
        duplicates = []
        last = sorted_list[0]
        for x in sorted_list[1:]:
            if x == last:
                duplicates.append(x)
            last = x
        return set(duplicates)
    

    Notes:

    • If you wish to preserve duplication count, get rid of the cast to 'set' at the bottom to get the full list
    • If you prefer to use generators, replace duplicates.append(x) with yield x and the return statement at the bottom (you can cast to set later)

提交回复
热议问题