当前位置: 首页 > 图灵资讯 > 行业资讯> python如何查询列表中不同元素个数?

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

发布时间:2026-03-22 22:15:31

collections可用于python.Counter(list)方法查询列表中不同元素的数量。

Counter的中文意思是计数器,这是一种常用于统计的数据类型。使用Counter后,我们的代码可以更简单、更容易读取。

示例:

#统计词频
colors=['red','blue','red','green','blue','blue']
result={}
forcolorincolors:
ifresult.get(color)==None:
result[color]=1
else:
result[color]+=1
print(result)
#{'red':2,'blue':3,'green':1}

使用Counter实现:

fromcollectionsimportCounter
colors=['red','blue','red','green','blue','blue']
c=Counter(colors)
print(dict(c))

输出结果

{'red': 2, 'blue': 3, 'green': 1}

请关注Python自学网了解更多Python知识。

相关文章

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

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

2026-03-22
如何用Python编写一副扑克牌?

如何用Python编写一副扑克牌?

2026-03-22
python解码后乱码的原因是什么?

python解码后乱码的原因是什么?

2026-03-22
如何用python画六边形?

如何用python画六边形?

2026-03-22
python怎么获取两个列表不同的元素?

python怎么获取两个列表不同的元素?

2026-03-20
python怎么使用wmi?

python怎么使用wmi?

2026-03-20