品易云推流 关闭
文章详情页
文章 > Python常见问题 > python如何查询列表中不同元素个数?

python如何查询列表中不同元素个数?

头像

yang

2020-05-18 14:53:593552浏览 · 0收藏 · 0评论

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知识请关注Python自学网

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图