Python 函数:查找数组中频率最高的数字(中频.数组.函数.率最高.查找...)

wufei1232025-07-26python238

python 函数:查找数组中频率最高的数字

第一段引用上面的摘要:

本文旨在提供一个高效的 Python 函数,用于查找给定数组中出现频率最高的数字。当多个数字具有相同频率时,该函数将返回这些数字中最大的一个。文章将详细解释该函数的实现原理,并提供示例代码和性能比较,同时讨论了不使用 defaultdict 的替代方案。

查找数组中频率最高的数字

在处理数据时,经常需要找出数组中出现频率最高的元素。如果存在多个频率相同的元素,则需要返回其中最大的一个。下面提供一个高效的 Python 函数来实现这个功能。

函数实现

该函数利用 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

代码解释:

  1. from collections import defaultdict: 导入 defaultdict 类,用于创建一个字典,当访问不存在的键时,会自动创建一个默认值(这里是 0)。
  2. count = defaultdict(int): 创建一个 defaultdict 对象,用于存储每个数字出现的次数。
  3. highest_rank = 0: 初始化 highest_rank 变量,用于存储当前频率最高的数字。初始值为 0。
  4. highest_rank_cnt = 0: 初始化 highest_rank_cnt 变量,用于存储当前最高频率的计数。初始值为 0。
  5. for num in arr:: 遍历输入数组 arr。
  6. cnt = count[num] + 1: 获取数字 num 的当前计数,并加 1。如果 num 之前没有出现过,count[num] 会返回默认值 0,然后加 1。
  7. count[num] = cnt: 更新数字 num 的计数。
  8. if cnt > highest_rank_cnt or (cnt == highest_rank_cnt and num > highest_rank):: 检查当前数字 num 的频率是否高于已知的最高频率,或者频率相同但 num 本身更大。
  9. highest_rank = num: 如果 num 的频率更高,则更新 highest_rank 为 num。
  10. highest_rank_cnt = cnt: 同时更新 highest_rank_cnt 为 num 的频率。
  11. return highest_rank: 返回频率最高的数字。

示例:

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 的替代方案

如果不希望使用 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 函数:查找数组中频率最高的数字的详细内容,更多请关注知识资源分享宝库其它相关文章!

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。