You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化批量命名数组的数值查找匹配函数代码?

简化方案

方案一:用列表整合数组,遍历查找

把分散的bf0-bf4变量换成列表统一存储,彻底消除重复的if-elif判断:

import numpy as np

# 用列表管理所有bf数组
bfs = []
# 初始化第一个数组
current_bf = np.arange(38, 75, 1)
bfs.append(current_bf)
# 生成后续4个数组
for _ in range(1, 5):
    current_bf = current_bf + 37
    bfs.append(current_bf)

def func(x):
    # 遍历列表,同时获取索引和对应数组
    for idx, bf in enumerate(bfs):
        if x in bf:
            return f"x is in bf{idx}"
    # 可选:返回未找到的提示
    return "x not found in any bf arrays"

方案二:利用区间特性直接计算(更高效)

观察到每个bf数组是连续数值区间,且每个区间的起始值比前一个大37,完全可以通过数学计算判断x所属区间,无需生成和存储数组:

def func(x):
    base_start = 38
    base_end = 74  # np.arange(38,75)的最大值是74(左闭右开特性)
    step = 37
    
    offset = x - base_start
    if offset < 0:
        return "x not found in any bf arrays"
    
    idx = offset // step
    # 检查索引是否在0-4范围内,且x不超过当前区间的最大值
    if 0 <= idx <= 4 and x <= base_end + step * idx:
        return f"x is in bf{idx}"
    
    return "x not found in any bf arrays"

两种方案都解决了原代码重复判断的问题:方案一保留了原有的数组检查逻辑,直观易理解;方案二则通过数学计算大幅提升效率,适合处理大量查询的场景。

内容的提问来源于stack exchange,提问作者Vilander Naoroibam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:30:16