开发者

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.开发者_StackOverflow中文版

So it would turn this

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

into this

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


>>> 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']


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

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


[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)), [])


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜