Python 找出列表中出现频率最高的数字(找出.数字.频率最高.列表中.Python...)
本文将提供一个高效的Python函数,用于找出列表中出现频率最高的数字。该函数在多个数字具有相同最高频率的情况下,返回数值较大的那个。我们将探讨一种使用 defaultdict 的优化方法,并提供不使用 defaultdict 的替代方案,同时对比不同方案的性能。
使用 defaultdict 找出最高频率数字以下代码展示了如何使用 collections.defaultdict 来高效地找出列表中出现频率最高的数字。
from collections import defaultdict def highest_rank(arr): count = defaultdict(int) highest_rank = 0 highest_rank_cnt = 0 for num in arr: cnt = count[num] + 1 count[num] = cnt if cnt > highest_rank_cnt or (cnt == highest_rank_cnt and num > highest_rank): highest_rank = num highest_rank_cnt = cnt return highest_rank
代码解释:
- defaultdict(int): 创建一个默认值为整数0的字典。这意味着,当我们尝试访问一个尚未存在的键时,它会自动创建一个值为0的键,避免了 KeyError 异常。
- 循环遍历 arr: 对于列表中的每个数字,我们增加其在 count 字典中的计数。
- 更新 highest_rank: 在每次迭代中,我们检查当前数字的计数是否大于当前最高频率 highest_rank_cnt,或者计数是否相等但当前数字大于 highest_rank。如果是,则更新 highest_rank 和 highest_rank_cnt。
示例:
print(highest_rank([9, 48, 1, 8, 44, 45, 32])) # 输出 48不使用 defaultdict 的替代方案
如果不希望使用 defaultdict,可以使用传统的 if num not in count 检查:
def highest_rank_no_defaultdict(arr): count = {} highest_rank = 0 highest_rank_cnt = 0 for num in arr: if num not in count: cnt = 1 else: cnt = count[num] + 1 count[num] = cnt if cnt > highest_rank_cnt or (cnt == highest_rank_cnt and num > highest_rank): highest_rank = num highest_rank_cnt = cnt return highest_rank
虽然这种方法也能得到正确的结果,但它比使用 defaultdict 稍微冗长且效率略低。
性能对比使用 defaultdict 的方法通常比使用 arr.count(i) 的方法效率更高。这是因为 arr.count(i) 在每次迭代中都会完整地遍历列表,而 defaultdict 只需要一次遍历即可统计所有元素的频率。以下是一个简单的性能测试:
import numpy as np from collections import defaultdict import time def highest_rank(arr): count = defaultdict(int) highest_rank = 0 highest_rank_cnt = 0 for num in arr: cnt = count[num]+1 count[num]=cnt if cnt > highest_rank_cnt or (cnt == highest_rank_cnt and num > highest_rank): highest_rank = num highest_rank_cnt = cnt return highest_rank def highest_rank_slow(arr): count_num = {} for i in arr: if i not in count_num: count_num[i] = 0 else: count_num[i] = arr.count(i) return max(count_num,key=lambda x:(count_num.get(x),x)) nums = list(np.random.randint(0,1000,10_000)) start_time = time.time() highest_rank(nums) end_time = time.time() print(f"highest_rank time: {end_time - start_time}") start_time = time.time() highest_rank_slow(nums) end_time = time.time() print(f"highest_rank_slow time: {end_time - start_time}")
测试结果表明,使用 defaultdict 的方法在处理大型列表时具有显著的性能优势。
总结本文提供了一个高效的Python函数,用于找出列表中出现频率最高的数字。通过使用 collections.defaultdict,我们可以避免重复遍历列表,从而提高性能。虽然不使用 defaultdict 也能实现相同的功能,但推荐使用 defaultdict 以获得更好的效率。在选择实现方法时,请根据实际需求和性能要求进行权衡。
以上就是Python 找出列表中出现频率最高的数字的详细内容,更多请关注知识资源分享宝库其它相关文章!