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

Python高效条件语句优化:多数据点下P值对比及最大差值匹配需求

优化批量数据点的差值计算逻辑实现

需求回顾

  • 遍历每一组连续的P[i]与P[i+1],计算符合规则的差值
  • 规则:
    • 若P[i] < P[i+1],差值为P[i+1] - P[i],对应BSP = SP[i],SSP = SP[i+1]
    • 若P[i] > P[i+1],差值为P[i] - P[i+1] - 50,对应BSP = SP[i+1],SSP = SP[i]
  • 最终选取最大差值对应的BSP和SSP

原代码问题

原代码通过硬编码逐个处理数据对,仅支持固定数量的输入数据,当数据量增大时,代码冗余、扩展性极差,无法高效处理。

优化后的实现

使用列表存储数据,通过循环批量处理所有连续数据对,同时实时跟踪最大差值及对应结果,代码如下:

# 用列表存储所有SP和P数据,支持任意数量的输入
sp_list = [100, 150, 200, 250]
p_list = [90, 40, 120, 150]

# 初始化最大差值及对应结果变量
max_diff = -float('inf')
target_bsp = None
target_ssp = None

# 遍历所有连续数据对(共len(p_list)-1组)
for i in range(len(p_list) - 1):
    current_p = p_list[i]
    next_p = p_list[i+1]
    current_sp = sp_list[i]
    next_sp = sp_list[i+1]
    
    # 计算差值及对应BSP、SSP
    if current_p > next_p:
        diff = current_p - next_p - 50
        bsp = next_sp
        ssp = current_sp
    else:
        diff = next_p - current_p
        bsp = current_sp
        ssp = next_sp
    
    # 更新最大差值及结果
    if diff > max_diff:
        max_diff = diff
        target_bsp = bsp
        target_ssp = ssp

# 输出最终结果
print(target_bsp)
print(target_ssp)

优化优势

  • 扩展性强:只需向sp_list和p_list中添加数据即可支持任意数量的输入点
  • 代码简洁:通过循环消除重复逻辑,减少冗余代码
  • 内存高效:无需存储所有差值及对应结果,仅实时跟踪当前最优解,适合处理超大量数据

内容的提问来源于stack exchange,提问作者Rakesh Mulik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:15:39