Python列表操作:如何修改除指定选中元素外的其余全部元素
代码修正方案
现有问题说明
- 原代码条件判断中错误使用了赋值运算符
=,需要改为相等判断运算符== - 缺少非目标元素的下调逻辑,遍历列表排除目标索引后统一减10即可实现需求
完整可运行代码
score = [70,60,80] action = ["one person off", 2, 200] def take_action(score, action): x = action[1] if action[0] == "one person off": # 目标索引元素上调30 score[x] += 30 # 其余所有元素下调10 for index in range(len(score)): if index != x: score[index] -= 10 take_action(score, action) print(score)
运行输出结果为[60, 50, 110],完全符合预期效果。
可选优化(不修改原列表)
如果需要避免函数直接修改传入的原列表,可以操作列表副本后返回新值:
def take_action(score, action): x = action[1] # 生成原列表的副本,不改动原数据 new_score = score.copy() if action[0] == "one person off": new_score[x] += 30 for index in range(len(new_score)): if index != x: new_score[index] -= 10 return new_score # 调用方式 score = take_action(score, action)
内容的提问来源于stack exchange,提问作者Bryn Owen-Conway
相关产品推荐
相关产品推荐

