Python中元素的频率列表
在本文中,我们将学习如何查找Python列表中元素的频率。Python列表的问题可以用不同的方法来解决。让我们看其中两种方法。
按照以下步骤编写代码:
- 用元素和一个空字典初始化列表。
- 迭代元素列表。
- 检查元素是否已经在字典中。
- 如果元素已经在字典中,则增加其计数。
- 如果元素不在字典中,则将其计数初始化为1。
- 打印字典。
例子
让我们看一下代码。
# initializing the list
random_list = ['A', 'A', 'B', 'C', 'B', 'D', 'D', 'A', 'B']
frequency = {}
# iterating over the list
for item in random_list:
# checking the element in dictionary
if item in frequency:
# incrementing the counr
frequency[item] += 1
else:
# initializing the count
frequency[item] = 1
# printing the frequency
print(frequency)
如果你运行上面的代码,你会得到以下结果。输出:
{'A': 3, 'B': 3, 'C': 1, 'D': 2}
按照以下方法解决问题。我们将使用一个模块方法来查找元素的频率。
- 导入
collections
模块。 - 初始化包含元素的列表。
- 使用
collections
模块中的Counter
获取元素的频率。 - 使用
dict()
将结果转换为字典,并打印频率。
示例
让我们看一下代码。
# importing the module
import collections
# initializing the list
random_list = ['A', 'A', 'B', 'C', 'B', 'D', 'D', 'A', 'B']
# using Counter to find frequency of elements
frequency = collections.Counter(random_list)
# printing the frequency
print(dict(frequency))
{'A': 3, 'B': 3, 'C': 1, 'D': 2}
如果你运行上述代码,你将得到以下结果。
输出
{'A': 3, 'B': 3, 'C': 1, 'D': 2}
结论
如果您对文章有任何问题,请在评论部分提出。