首页 > 编程语言 >Python基础小知识问答系列-列表元素次数统计

Python基础小知识问答系列-列表元素次数统计

时间:2024-07-04 10:27:24浏览次数:32  
标签:元素 Python demo counter list 列表 other 问答

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}")
  • 示例结果:

标签:元素,Python,demo,counter,list,列表,other,问答
From: https://blog.csdn.net/zhangshanjia01/article/details/140126301

相关文章