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

发布时间:2022-06-09 09:40:19 人气:255 作者:多测师

  python中可以使用collections.Counter(list)方法查询列表中不同元素个数。

  Counter中文意思是计数器,也就是我们常用于统计的一种数据类型,在使用Counter之后可以让我们的代码更加简单易读。

  示例:

  #统计词频

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

  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相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线