可以使用Counter对象来统计列表元素出现的次数,并使用sorted函数将结果从大到小排序。

示例代码:

from collections import Counter

lst = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']

count = Counter(lst)
result = sorted(count.items(), key=lambda x: x[1], reverse=True)

print(result)

输出结果:

[('apple', 3), ('banana', 2), ('orange', 1)]

其中,count.items()返回一个包含元素和出现次数的元组列表,sorted函数使用key参数指定按照出现次数排序,并设置reverse参数为True表示降序排列。

python 统计列表元素出现的次数 并返回从大到小的排序的列表

原文地址: http://www.cveoy.top/t/topic/Kwo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录