简体   繁体   English

Python按列表中字符串的出现次数对字符串进行排序

[英]Python sort strings by count of appearances of the strings in the list

I have a list of strings tags which I wish to sort by count of appearances of the strings in the list. 我有一个字符串tags列表,我希望按列表中字符串的出现次数进行排序。

I have tried: 我努力了:

Creating the list of unique strings, 创建唯一字符串列表,

uniqueTags = set(tags)

Then creating a second list with the counts for each of the unique string 然后创建第二个列表,其中包含每个唯一字符串的计数

countList = []
for items in uniqueTags:
    countList.append(tags.count(items))

but then I am not sure how to sort. 但是我不确定如何排序。

Use collections.Counter(...) instead. 请改用collections.Counter(...)

In [18]: from collections import Counter

In [19]: m = ['a', 'b', 'a', 'b', 'c']

In [20]: Counter(m).most_common()
Out[20]: [('a', 2), ('b', 2), ('c', 1)]

Counter.most_common() returns a list of a tuple such that the first element is the string and the second is it's count and the list is ordered by the count. Counter.most_common()返回一个元组的列表,这样第一个元素是字符串,第二个元素是字符串,并且该列表按计数排序。

In [21]: m2 = ['a', 'b', 'a', 'b', 'c', 'b']

In [22]: Counter(m2).most_common()
Out[22]: [('b', 3), ('a', 2), ('c', 1)]

Just to get a list of items, you could do 只是为了获得一个项目列表,你可以做到

In [28]: [elem for elem, _ in Counter(m2).most_common()]
Out[28]: ['b', 'a', 'c']

If you're looking to sort the list you got, change your method to something like 如果要对列表进行排序,请将方法更改为

In [23]: final_list = []

In [24]: for elem in set(m2):
    ...:     final_list.append((elem, m2.count(elem)))
    ...:     

In [25]: from operator import itemgetter

In [26]: sorted(final_list, key=itemgetter(1))
Out[26]: [('c', 1), ('a', 2), ('b', 3)]

In [27]: sorted(final_list, key=itemgetter(1), reverse=True)
Out[27]: [('b', 3), ('a', 2), ('c', 1)]

Here is one way to do it: 这是一种方法:

from collections import Counter
from operator import itemgetter
get_val = itemgetter(0)

def retrieve_unique_sorted_by_count(lst)
    return [get_val(x) for x in Counter(lst).most_common()]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM