我有一个字符串列表,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)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句