1. 问题:
- 怎样统计列表中元素出现次数?
- 怎样获得列表中元素出现次数排在前n的元素?
- 怎样汇总两个列表中元素出现次数的信息?
2. 解决方法:
使用collections模块中的Counter函数。
- 示例:
import collections
demo_list = ["张共", "欣欣", "菲菲", "潇潇", "阿志", "吾知", "江红", "菲菲", "阿里", "吾知", "潇潇","吾知", "江红", "菲菲"]
demo_list_other = ["张共", "欣欣", "菲菲", "张共-江苏", "菲菲", "阿里", "吾知", "潇潇", "吾知", "江红", "菲菲"]
# 统计每个元素出现次数
counter = collections.Counter(demo_list)
print(f"demo_list列表中统计每个元素出现次数:{counter}")
counter_other = collections.Counter(demo_list_other)
print(f"demo_list_other列表中统计每个元素出现次数:{counter_other}")
# 筛选出现次数排在前3的元素
print(f"demo_list列表中元素出现次数排在前3的元素是:{counter.most_common(3)}")
print(f"demo_list_other列表中元素出现次数排在前3的元素是:{counter_other.most_common(3)}")
# 汇总两个列表元素出现次数
total_counter = counter + counter_other
print(f"demo_list列表和demo_list_other列表中元素次数汇总结果:{total_counter}")
- 示例结果: