Python 列表重复元素统计 - 使用 Counter 类
使用Python的collections模块中的Counter类来统计列表中一列中重复字段和其数量。具体步骤如下:\n1. 导入collections模块中的Counter类:`from collections import Counter`\n2. 定义列表:`data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']`\n3. 使用Counter类统计列表中一列中重复字段和其数量:`counter = Counter(data)`\n4. 打印结果:`print(counter)`\n\n完整代码如下所示:\n\npython\nfrom collections import Counter\n\ndata = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']\ncounter = Counter(data)\nprint(counter)\n\n\n运行结果如下所示:\n\n\nCounter({'apple': 3, 'banana': 2, 'orange': 1})\n\n\n可以看到,结果中每个字段及其对应的数量都以键值对的形式进行显示。
原文地址: https://www.cveoy.top/t/topic/ptsw 著作权归作者所有。请勿转载和采集!