Reputation: 1568
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?
Upvotes: 0
Views: 148
Reputation: 414079
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)]
Upvotes: 1