How to sort Counter by value? – python

Other than doing list comprehensions of reversed list comprehension, is there a pythonic way to sort Counter by value? If so, it is faster than this: >>> from collections import Counter >>> x = Counter({‘a’:5, ‘b’:3, ‘c’:7}) >>> sorted(x) [‘a’, ‘b’, ‘c’] >>> sorted(x.items()) [(‘a’, 5), (‘b’, 3), (‘c’, 7)] >>> [(l,k) for k,l in … Read more

How to count the frequency of the elements in an unordered list?

I need to find the frequency of elements in an unordered list a = [1,1,1,1,2,2,2,2,3,3,4,5,5] output-> b = [4,4,2,1,2] Also I want to remove the duplicates from a a = [1,2,3,4,5] 34 Answers 34 In Python 2.7 (or newer), you can use collections.Counter: import collections a = [1,1,1,1,2,2,2,2,3,3,4,5,5] counter=collections.Counter(a) print(counter) # Counter({1: 4, 2: 4, … Read more