rectangletangle
rectangletangle

Reputation: 52911

Sorting Lists by Repetitions in Python

I have a list that contains multiple repeated items. I'm trying to sort the list by giving items with the most repetitions priority.

So it would turn this

['a', 'b', 'c', 'a', 'b', 'a', 'd']

into this

['a', 'a', 'a', 'b', 'b', 'c', 'd']

Upvotes: 2

Views: 386

Answers (4)

John La Rooy
John La Rooy

Reputation: 304137

>>> from collections import Counter
>>> [k for k,v in Counter(['a', 'b', 'c', 'a', 'b', 'a', 'd']).most_common() for i in xrange(v)]
['a', 'a', 'a', 'b', 'b', 'c', 'd']

This is possibly easier to follow

>>> counter = Counter(['a', 'b', 'c', 'a', 'b', 'a', 'd'])
>>> sorted(counter.elements(), key=counter.get, reverse=True)
['a', 'a', 'a', 'b', 'b', 'c', 'd']

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798556

[v for (v, c) in sorted(((x, list(y)) for (x, y) in
  itertools.groupby(sorted(['a', 'b', 'c', 'a', 'b', 'a', 'd']))),
  key=lambda x: len(x[1]), reverse=True) for z in c]

EDIT:

Now with sum()!

sum((c for (v, c) in sorted(((x, list(y)) for (x, y) in
  itertools.groupby(sorted(['a', 'b', 'c', 'a', 'b', 'a', 'd']))),
  key=lambda x: len(x[1]), reverse=True)), [])

Upvotes: 2

GWW
GWW

Reputation: 44093

d = {}
for a in l:
    d[a] += d.setdefault(a,0)

l.sort(key = lambda k: (d[k],k), reverse = True)

Upvotes: 5

Jim Brissom
Jim Brissom

Reputation: 32919

l = ['a', 'b', 'c', 'a', 'b', 'a', 'd']
sorted_list = [item for item in sorted(l, key=lambda x: l.count(x), reverse=True)]

While this is a simple solution, mind the complexity of counting every element when using large lists.

Upvotes: 1

Related Questions