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

Python代码求助:列表及子列表整数平方替换后输出未更新

问题分析与解决

你的代码完全没生效,核心是两个低级错误:

1. 运算符用错了

所有需要更新值的地方你都写了==(这是用来判断两边是否相等的比较运算符),它只会返回True/False,根本不会修改原变量的值。必须换成=(赋值运算符),才能把平方后的结果存回列表。

2. 嵌套列表处理逻辑乱了

else分支里硬编码了new_list[2]和new_list[5],这会导致每次遇到嵌套列表时都重复处理这两个固定位置的元素,而不是处理当前循环到的那个嵌套列表。应该直接操作当前循环的元素。


修正后的代码

new_list = [1,3, [0,10], 8, 9, [13]]
for i in range(len(new_list)):
    if type(new_list[i]) == int:
        # 把==换成=,完成赋值
        new_list[i] = new_list[i] ** 2
    else:
        # 处理当前循环到的嵌套列表,不是固定索引的
        nested_list = new_list[i]
        for j in range(len(nested_list)):
            nested_list[j] = nested_list[j] ** 2
print(new_list)

运行后输出:[1, 9, [0, 100], 64, 81, [169]],符合预期。


更灵活的优化版本

用isinstance代替type判断类型,它能处理继承场景,适用性更广;同时用enumerate遍历,代码更简洁:

new_list = [1,3, [0,10], 8, 9, [13]]
for idx, element in enumerate(new_list):
    if isinstance(element, int):
        new_list[idx] = element ** 2
    elif isinstance(element, list):
        for nested_idx, num in enumerate(element):
            element[nested_idx] = num ** 2
print(new_list)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:40:57