Sorting a List of List in Python by frequency

回眸只為那壹抹淺笑 提交于 2021-02-05 07:42:48

问题


I am trying to sort a list of list items in Python by the frequency of the occurrence The unsorted list looks something like this :

a=[     ['item1', 'item2', 'element2'],
        ['item3', 'item4', 'element3'],
        ['item5', 'item6', 'element1'],
        ['item7', 'item8', 'element3']]

I would like to sort by the frequency of the 3rd element of the list. So, the result list after sorting, would look something this :

result = [  ['item3', 'item4', 'element3'],
            ['item7', 'item8', 'element3'],
            ['item1', 'item2', 'element2'],
            ['item5', 'item6', 'element1']]

I am not an expert with Python. Any idea, how can it be done?


回答1:


You'll have to collect frequencies first; a collections.Counter() object would do this nicely. You can then look up frequencies and order by that:

from collections import Counter

freq = Counter(item[-1] for item in a)
result = sorted(a, key=lambda i: freq[i[-1]], reverse=True)

Here freq holds counts for the last element in each nested list, which we then use a sort key, in reverse order (most frequent sorted first).

Demo:

>>> from collections import Counter
>>> a=[     ['item1', 'item2', 'element2'],
...         ['item3', 'item4', 'element3'],
...         ['item5', 'item6', 'element1'],
...         ['item7', 'item8', 'element3']]
>>> freq = Counter(item[-1] for item in a)
>>> sorted(a, key=lambda i: freq[i[-1]], reverse=True)
[['item3', 'item4', 'element3'], ['item7', 'item8', 'element3'], ['item1', 'item2', 'element2'], ['item5', 'item6', 'element1']]
>>> from pprint import pprint
>>> pprint(_)
[['item3', 'item4', 'element3'],
 ['item7', 'item8', 'element3'],
 ['item1', 'item2', 'element2'],
 ['item5', 'item6', 'element1']]



回答2:


Take a look at collections.Counter

Example:

wordlist = ['foo', 'bar', 'foo', 'baz']
import collections
counter = collections.Counter(wordlist)
counter.most_common()

returns:

[('foo', 2), ('baz', 1), ('bar', 1)]



回答3:


I think there is no need to import Counter or anything else, just define your own key function which will just return the last element of a list, so to make the sorting based on that element...

Hence, you could use 'sorted' with the key function last_element (that you defined) like this:

def last_element(x): return x[-1]

sorted(a, key=last_element, reverse=True)

and you get:

[['item3', 'item4', 'element3'], ['item7', 'item8', 'element3'], ['item1', 'item2', 'element2'], ['item5', 'item6', 'element1']]

If you don't want to define a new function you can use lambda (similar as shown in another answer), so the solution in just one line would be:

sorted(a, key=lambda x: x[-1], reverse=True)


来源:https://stackoverflow.com/questions/23762609/sorting-a-list-of-list-in-python-by-frequency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!