You need to enable JavaScript to run this app. NumPy Python数组条件格式化:按order末元素追加关联值
优惠活动
大模型
产品
解决方案
定价
更多

NumPy Python数组条件格式化:按order末元素追加关联值

NumPy 数组条件格式化实现方案

核心实现逻辑为:先提取目标数组的末尾元素值,匹配对应追加规则,同步完成目标数组和value数组的元素追加,完全对齐给出的期望输出效果。

通用实现代码

import numpy as np

# 初始化输入数组
order = np.array([0,1,0,0,0])
order1 = np.array([0,1,0,0,1])
value = np.array([10,55,30,3,10])

def conditional_array_update(target_order, current_value):
    # 读取目标数组的末尾元素
    last_num = target_order[-1]
    # 匹配对应追加规则
    if last_num == 0:
        # 末位为0时:目标数组追加1,value数组追加20
        updated_order = np.append(target_order, 1)
        updated_value = np.append(current_value, 20)
    elif last_num == 1:
        # 末位为1时:目标数组追加0,value数组追加15
        updated_order = np.append(target_order, 0)
        updated_value = np.append(current_value, 15)
    else:
        raise ValueError("数组末尾元素仅支持0或1两类取值")
    return updated_order, updated_value

效果验证

分别传入两个初始数组执行函数,即可得到对应期望结果:

# 处理末位为0的order数组
res_order, res_value1 = conditional_array_update(order, value)
print("末位为0的处理结果:")
print("order数组:", res_order)  # 输出 [0 1 0 0 0 1]
print("value数组:", res_value1) # 输出 [10 55 30 3 10 20]

# 处理末位为1的order1数组
res_order1, res_value2 = conditional_array_update(order1, value)
print("末位为1的处理结果:")
print("order1数组:", res_order1) # 输出 [0 1 0 0 1 0]
print("value数组:", res_value2) # 输出 [10 55 30 3 10 15]

提示:你原标注的分支注释与对应数组的实际末位值存在错位,上述实现完全匹配给出的数值形式的期望输出。


内容的提问来源于stack exchange,提问作者tony selcuk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 14:54:03