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

Python中按指定格式向列表追加元素问题求助

问题:修正列表索引收集的格式问题

有两个列表Pr_cap_t和MaxPrnew,需要找出不满足MaxPrnew > Pr_cap_t的索引值,并按指定格式追加到列表中。以下是当前代码、当前输出及期望输出:

当前代码

Pr_cap_t=[5051.061086369891,
 5046.295040175788,
 5072.5758312061325,
 5055.713625152885,
 5056.625327627877]

MaxPrnew=[241.08095445711552,
 1726.9903228626436,
 1232.262749719154,
 484.3360494454877,
 1232.262749719154]


Cond_t=[]
false_indices = [[]]

for i in range(len(MaxPrnew)):  
    Cond1 = MaxPrnew[i] > Pr_cap_t[i]
    Cond_t.append(Cond1) 
    if not Cond1: 
        false_indices.append(i)

print("false_indices =",false_indices)

当前输出

false_indices = [[], 0, 1, 2, 3, 4]

期望输出

false_indices = [[], [0, 1, 2, 3, 4]]

修正方案

原代码的问题在于:每次找到不满足条件的索引时,直接将单个索引值追加到外层列表false_indices中,而不是将索引存入一个子列表后再追加到外层列表。

修正后的代码(方法一)

Pr_cap_t=[5051.061086369891,
 5046.295040175788,
 5072.5758312061325,
 5055.713625152885,
 5056.625327627877]

MaxPrnew=[241.08095445711552,
 1726.9903228626436,
 1232.262749719154,
 484.3360494454877,
 1232.262749719154]

Cond_t=[]
false_indices = [[]]
# 临时列表收集所有不满足条件的索引
temp_indices = []

for i in range(len(MaxPrnew)):  
    Cond1 = MaxPrnew[i] > Pr_cap_t[i]
    Cond_t.append(Cond1) 
    if not Cond1: 
        temp_indices.append(i)

# 将收集好的索引列表追加到false_indices
false_indices.append(temp_indices)

print("false_indices =", false_indices)

修正后的代码(方法二)

Pr_cap_t=[5051.061086369891,
 5046.295040175788,
 5072.5758312061325,
 5055.713625152885,
 5056.625327627877]

MaxPrnew=[241.08095445711552,
 1726.9903228626436,
 1232.262749719154,
 484.3360494454877,
 1232.262749719154]

Cond_t=[]
false_indices = [[]]
# 先添加一个空子列表用于存放索引
false_indices.append([])

for i in range(len(MaxPrnew)):  
    Cond1 = MaxPrnew[i] > Pr_cap_t[i]
    Cond_t.append(Cond1) 
    if not Cond1: 
        # 直接往第二个子列表中追加索引
        false_indices[1].append(i)

print("false_indices =", false_indices)

两种方法都能得到期望的输出格式,核心是确保所有不满足条件的索引都被存入同一个子列表,再添加到外层列表中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:17:03