簡體   English   中英

Python按列表中字符串的出現次數對字符串進行排序

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

我有一個字符串tags列表,我希望按列表中字符串的出現次數進行排序。

我努力了:

創建唯一字符串列表,

uniqueTags = set(tags)

然后創建第二個列表,其中包含每個唯一字符串的計數

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

但是我不確定如何排序。

請改用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()返回一個元組的列表,這樣第一個元素是字符串,第二個元素是字符串,並且該列表按計數排序。

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

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

只是為了獲得一個項目列表,你可以做到

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

如果要對列表進行排序,請將方法更改為

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

這是一種方法:

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