Get a unique list of items that occur more than once in a list

后端 未结 7 1057
深忆病人
深忆病人 2020-12-03 17:51

I have a list of items:

mylist = [\'A\',\'A\',\'B\',\'C\',\'D\',\'E\',\'D\']

I want to return a unique list of items that appear more than

相关标签:
7条回答
  • 2020-12-03 18:17

    You can use collections.Counter to do what you have described easily:

    from collections import Counter
    mylist = ['A','A','B','C','D','E','D']
    cnt = Counter(mylist)
    print [k for k, v in cnt.iteritems() if v > 1]
    # ['A', 'D']
    
    0 讨论(0)
  • 2020-12-03 18:21

    Might not be as fast as internal implementations, but takes (almost) linear time (since set lookup is logarithmic)

    mylist = ['A','A','B','C','D','E','D']
    myset = set()
    dups = set()
    for x in mylist:
        if x in myset:
            dups.add(x)
        else:
            myset.add(x)
    dups = list(dups)
    print dups
    
    0 讨论(0)
  • 2020-12-03 18:24
    >>> mylist = ['A','A','B','C','D','E','D']
    >>> set([i for i in mylist if mylist.count(i)>1])
    set(['A', 'D'])
    
    0 讨论(0)
  • 2020-12-03 18:24
    import collections
    cc = collections.Counter(mylist) # Counter({'A': 2, 'D': 2, 'C': 1, 'B': 1, 'E': 1})
    cc.subtract(cc.keys())           # Counter({'A': 1, 'D': 1, 'C': 0, 'B': 0, 'E': 0})
    cc += collections.Counter()      # remove zeros (trick from the docs)
    print cc.keys()                  # ['A', 'D']
    
    0 讨论(0)
  • 2020-12-03 18:28

    Using a similar approach to others here, heres my attempt:

    from collections import Counter
    
        def return_more_then_one(myList):
             counts = Counter(my_list)
             out_list = [i for i in counts if counts[i]>1]
             return out_list
    
    0 讨论(0)
  • 2020-12-03 18:28

    It can be as simple as ...

    print(list(set([i for i in mylist if mylist.count(i) > 1])))
    
    0 讨论(0)
提交回复
热议问题