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

Python中满足特定条件时向列表插入0的实现方法

问题解决:替换特定索引对应的值为0

需求:现有列表J和numpy数组inv_r,生成新列表inv_r2时,只要J中出现J[0][0]的值(此处为0),就插入0.0,而非原数组对应的值。

当前代码

import numpy as np

inv_r2=[]
J=[[0, 2, 0, 6, 7, 9, 10]]
index=[[]]

inv_r=np.array([[19436.34013609, 20118.9577258 , 20606.73993168, 19471.35381891,
    20144.97489348, 19518.70812614, 20685.76698401, 20032.65982561,
    19694.87399016, 20191.66204251, 20289.75387733, 19436.34013609]])

for i in range(0,len(J[len(index)-1])):
    inv_r1=inv_r[0][J[len(index)-1][i]]
    inv_r2.append(inv_r1)
print(inv_r2)

当前输出

[19436.34013609, 20606.73993168, 19436.34013609, 20685.76698401, 20032.65982561, 20191.66204251, 20289.75387733]

期望输出

[0.0, 20606.73993168, 0.0, 20685.76698401, 20032.65982561, 20191.66204251, 20289.75387733]

修改后的代码

import numpy as np

inv_r2=[]
J=[[0, 2, 0, 6, 7, 9, 10]]
target_val = J[0][0]  # 定义需要替换的目标值

inv_r=np.array([[19436.34013609, 20118.9577258 , 20606.73993168, 19471.35381891,
    20144.97489348, 19518.70812614, 20685.76698401, 20032.65982561,
    19694.87399016, 20191.66204251, 20289.75387733, 19436.34013609]])

# 遍历J的第一个子列表中的每个元素
for idx in J[0]:
    if idx == target_val:
        inv_r2.append(0.0)
    else:
        inv_r2.append(inv_r[0][idx])
print(inv_r2)

说明

  1. 定义target_val = J[0][0]明确需要替换的目标值,代码更易读且灵活,后续修改目标值只需调整这一行。
  2. 简化循环逻辑:直接遍历J[0]中的每个索引值,无需通过长度计算生成循环范围,代码更简洁直观。
  3. 添加条件判断:当当前索引等于目标值时,向inv_r2添加0.0,否则添加原数组对应位置的值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 18:13:22