
第一段引用上面的摘要:
本文旨在提供一个高效的 Python 函数,用于查找给定数组中出现频率最高的数字。当多个数字具有相同频率时,该函数将返回这些数字中最大的一个。文章将详细解释该函数的实现原理,并提供示例代码和性能比较,同时讨论了不使用 defaultdict 的替代方案。
在处理数据时,经常需要找出数组中出现频率最高的元素。如果存在多个频率相同的元素,则需要返回其中最大的一个。下面提供一个高效的 Python 函数来实现这个功能。
该函数利用 collections.defaultdict 来统计每个数字出现的次数,并在遍历数组的过程中,动态更新频率最高的数字。
立即学习“Python免费学习笔记(深入)”;
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代码解释:
示例:
勾股OA是一款基于ThinkPHP6 + Layui + MySql打造的实用的开源的企业办公系统,开箱即用,使用勾股OA可以简单快速地建立企业级的办公自动化系统。 办公自动化系统是员工及管理者使用频率最高的应用系统,可以极大提高公司的办公效率,我们立志为中小企业提供开源好用的办公自动化系统,帮助企业节省数字化、信息化办公的成本。 系统特点1、系统各功能模块,一目了然,操作简单;通用型的后台权
21
arr = [9, 48, 1, 8, 44, 45, 32, 48] result = highest_rank(arr) print(result) # 输出 48
与使用 arr.count(i) 的方法相比,使用 defaultdict 的方法效率更高。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"Time taken by highest_rank: {end_time - start_time:.4f} seconds")
start_time = time.time()
highest_rank_slow(nums)
end_time = time.time()
print(f"Time taken by highest_rank_slow: {end_time - start_time:.4f} seconds")在包含 10,000 个随机数的数组上运行上述代码,可以观察到 highest_rank 函数的执行速度明显快于 highest_rank_slow 函数。
如果不希望使用 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 的代码更简洁,效率也更高。
本文提供了一个高效的 Python 函数,用于查找数组中频率最高的数字。该函数利用 collections.defaultdict 来提高性能,并提供了不使用 defaultdict 的替代方案。在实际应用中,可以根据具体的需求选择最适合的实现方式。
以上就是Python 函数:查找数组中频率最高的数字的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号