简体   繁体   中英

Find the occurrences of unique element in list in python

For finding occurrences of unique element in a list in python i used

import collections

a='77888'
b=list(collections.Counter(a).items())

but the b is sorted in order of occurences b=[('8',3),('7',2)] . But is want unsorted b . How can i achieve this?

To find unique items in the list a :

from collections import Counter

unique_items = [item for item, count in Counter(a).items() if count == 1]

If input is sorted then you could use itertools.groupby() :

from itertools import groupby

unique_items = [key for key, group in groupby(a) if len(list(group)) == 1]

If you want to get items and their frequencies in the same order as in the input, you could define OrderedCounter :

from collections import Counter, OrderedDict

class OrderedCounter(Counter, OrderedDict):
    pass

then:

>>> list(OrderedCounter('77888').items())
[('7', 2), ('8', 3)]
>>> list(OrderedCounter('88877').items())
[('8', 3), ('7', 2)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM