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

标签 python python-2.7

我有一个字符串列表 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)]

关于Python 根据字符串在列表中出现的次数对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19683079/

相关文章:

Python 奇怪地打印字节

python - Pandas 按列将 CSV 拆分为多个 CSV(或 DataFrames)

python - 如果值在列表 pandas 中,则 bool 向量

python - Python 中的 logging.warn 和 logging.warning 有什么区别?

python - 如何在 python 中正确操作相对 URL?

python - Pandas 根据级别名称连接多索引列

python - 根据日期范围合并数据框

python - 无法将 Jupyter 笔记本导出到 Azure ML Studio 中的 Python 脚本

python - python 中的振荡积分

python - 将项目保存到只读存储时是否应该包含 .pyc 字节代码?