利用Python字典的键值对来进行统计。
逻辑就是,生成一个字典,将要统计的列表作为字典的键,然后对字典该键进行赋值,赋值方法采用字典的dict.get()函数。
Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。

dict.get(key, default=None)

  • key -- 字典中要查找的键。
  • default -- 如果指定键的值不存在时,返回该默认值。
a_list = ['dog', 'cat', 'dog', 'pig', 'pig', 'dog']
freq_dict = {}
for x in a_list :
    freq_dict[x] = freq_dict.get(x, 0) + 1
print(freq_dict) 

out

{'dog': 3, 'cat': 1, 'pig': 2}

相关文章:

  • 2022-12-23
  • 2021-07-31
  • 2021-12-09
  • 2022-12-23
  • 2022-12-23
  • 2021-07-30
  • 2022-02-17
  • 2022-12-23
猜你喜欢
  • 2021-08-08
  • 2021-12-06
  • 2022-12-23
  • 2021-05-18
  • 2021-07-18
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案