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查询列表中不同元素个数的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!