在 Python 中查找列表中给定元素的频率总和
pythonserver side programmingprogramming更新于 2025/11/23 21:32:17
给定的列表有许多重复项。我们感兴趣的是找出列表中重复出现的某些此类项目的频率总和。以下是实现此目的的方法。
使用 sum
我们有两个列表。一个包含值列表,另一个包含需要从第一个列表中检查频率的值。因此,我们创建一个 for 循环来计算第二个列表中的元素在第一个列表中出现的次数,然后应用 sum 函数来获取最终的频率总和。
示例
chk_list= ['Mon', 'Tue']
big_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue']
# Apply sum
res = sum(big_list.count(elem) for elem in chk_list)
# 打印输出
print("Given list to be analysed: \n", big_list)
print("Given list to with values to be analysed:\n", chk_list)
print("Sum of the frequency: ", res)
输出
运行上述代码得到以下结果 −
Given list to be analysed: ['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue'] Given list to with values to be analysed: ['Mon', 'Tue'] Sum of the frequency: 5
使用 collections.Counter
collections 模块中的 Counter 函数可以通过将其应用于需要分析其值的列表,同时循环遍历仅包含需要确定频率的元素的较小列表来获得所需的结果。
示例
from collections import Counter
chk_list= ['Mon', 'Tue']
big_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue']
# Apply Counter
res = sum(Counter(big_list)[x] for x in chk_list)
# 打印输出
print("Given list to be analysed: \n", big_list)
print("Given list to with values to be analysed:\n", chk_list)
print("Sum of the frequency: ", res)
输出
运行上述代码得到以下结果 −
Given list to be analysed: ['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue'] Given list to with values to be analysed: ['Mon', 'Tue'] Sum of the frequency: 5
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

