使用 Python 中的字典计算列表中的频率

pythonserver side programmingprogramming更新于 2025/10/19 3:24:17

在本文中,我们开发了一个程序来计算列表中每个元素的频率。

使用字典

在这里,我们将项目捕获为字典的键,并将其频率作为值。

示例

list = ['a','b','a','c','d','c','c']
frequency = {}
for item in list:
   if (item in frequency):
      frequency[item] += 1
   else:
      frequency[item] = 1
for key, value in frequency.items():
   print("% s -> % d" % (key, value))

输出

运行上述代码得到以下结果 −

a -> 2
b -> 1
c -> 3
d -> 1

使用 count()

这里我们使用内置的 count() 函数来计算列表中某个项目的出现次数。

输出

list = ['a','b','a','c','d','c','c']
frequency = {}
for item in list:
   frequency[item] = list.count(item)
for key, value in frequency.items():
   print("% s -> % d" % (key, value))

运行上述代码得到以下结果 >

a -> 2
b -> 1
c -> 3
d -> 1

相关文章


有用资源