
本文将提供一个高效的Python函数,用于找出列表中出现频率最高的数字。该函数在多个数字具有相同最高频率的情况下,返回数值较大的那个。我们将探讨一种使用 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代码解释:
示例:
立即学习“Python免费学习笔记(深入)”;
print(highest_rank([9, 48, 1, 8, 44, 45, 32])) # 输出 48
如果不希望使用 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 找出列表中出现频率最高的数字的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号