Keep duplicates in a list in Python

后端 未结 4 1973
悲哀的现实
悲哀的现实 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: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]
    

提交回复
热议问题