if/else分支配对条件操作错误:多条件替换列表数值失效问题
问题原因
- 条件判断的优先级顺序错误:
if...elif...分支会按从上到下的顺序匹配,只要命中一个分支就会跳过剩下所有判断。同时是3和4的倍数的元素,会先命中第一个i % 3 == 0的条件被替换为'a',永远不会走到第三个同时匹配的分支。 - 原代码中仅修改了循环内的临时变量
i,不会修改传入的原列表内容,如果需要保留修改后的结果需要额外存储。
修复代码
版本1:直接打印结果
y = list(range(0,25)) def some(x): decim_3 = 3 decim_4 = 4 output = [] for i in x: # 优先级最高的公共倍数条件放最前面 if i % decim_3 == 0 and i % decim_4 == 0: output.append('c') elif i % decim_3 == 0: output.append('a') elif i % decim_4 == 0: output.append('b') else: output.append(str(i)) print(', '.join(output)) some(y)
版本2:返回修改后的列表
y = list(range(0,25)) def some(x): decim_3 = 3 decim_4 = 4 res = [] for i in x: if i % decim_3 == 0 and i % decim_4 == 0: res.append('c') elif i % decim_3 == 0: res.append('a') elif i % decim_4 == 0: res.append('b') else: res.append(i) return res # 调用示例 processed_list = some(y) print(processed_list)
运行结果
修复后输出为:
c, 1, 2, a, b, 5, a, 7, b, a, 10, 11, c, 13, 14, a, b, 17, a, 19, b, a, 22, 23, c
符合需求:0、12、24这三个同时为3和4倍数的元素被替换为'c'。
内容的提问来源于stack exchange,提问作者maric92
相关产品推荐
相关产品推荐

