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

如何将Python嵌套列表推导式改写为等价的多层for循环实现

列表推导式改写为嵌套for循环的实现

原列表推导式的逻辑等价于以下嵌套for循环写法,拆分后每层逻辑职责更清晰,可读性更高:

import numpy as np # 若此前已导入numpy可省略该行

average_mae_history = []
# 第一层遍历每个epoch的索引
for i in range(num_epochs):
    # 收集当前epoch对应的所有MAE值
    epoch_mae_list = []
    for x in all_mae_histories:
        epoch_mae_list.append(x[i])
    # 计算当前epoch的平均MAE并加入结果列表
    avg_mae = np.mean(epoch_mae_list)
    average_mae_history.append(avg_mae)

如果你希望兼顾简洁度和可读性,也可以只拆分外层循环,保留内层的短列表推导式:

average_mae_history = []
for i in range(num_epochs):
    current_epoch_maes = [x[i] for x in all_mae_histories]
    average_mae_history.append(np.mean(current_epoch_maes))
  • 以上两种改写方式的执行结果和原列表推导式完全一致
  • 拆分循环后可方便地在逻辑中插入调试打印、异常处理等额外操作,更便于后续维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:18:01