导语:
本文主要介绍了关于python如何查询列表中不同元素个数?的相关知识,包括python为什么叫爬虫,以及python列表删除多个元素这些编程知识,希望对大家有参考作用。
python中可以使用collections.Counter(list)方法查询列表中不同元素个数。
Counter中文意思是计数器,是我们经常用来统计的一种数据类型。使用Counter之后,可以让我们的代码更易读。
示例:
#统计词频
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
result = {}
for color in colors:
if result.get(color)==None:
result[color]=1
else:
result[color]+=1
print (result)
#{'red': 2, 'blue': 3, 'green': 1}
用Counter实现:
from collections import Counter
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
c = Counter(colors)
print (dict(c))
输出结果
{'red': 2, 'blue': 3, 'green': 1}
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ 如何在python中找到所有数字?09/26
- ♥ 如何使用python函数定义09/10
- ♥ python字符串的驻留机制是什么09/30
- ♥ 如何在python中表示大于或等于08/14
- ♥ python读取txt乱码的解决方法11/24
- ♥ 如何在python中删除“\ n”08/19
内容反馈