Python while循环输出不符合预期,无循环时代码运行正常
分析你的嵌套列表操作代码
先帮你理清楚这段代码的运行逻辑,以及你觉得“奇怪”的点——其实你说的“没有while循环也能正常运行”是完全合理的,因为外层的while只是把相同的逻辑重复执行了两次而已,手动展开步骤也能达到一样的效果。
先看代码的核心逻辑
你的目标是:每次循环把target里的每个子列表复制一份(让整个target翻倍),然后给每个子列表依次添加add里的元素,之后再把add也翻倍,重复这个过程两次。
先把你的代码贴出来方便查看:
target = [[1],] add = [2,4] count = 0 while count < 2: temp = [] for i in target: temp += [i, i] target = temp[:] print('before', target) idx = 0 while idx < len(target): target[idx].append(add[idx]) idx += 1 print('after', target) add += add count += 1
逐次拆解循环过程
第一次循环(count=0)
- 初始状态:
target = [[1]],add = [2,4] - 先把
target翻倍:遍历target里的每个子列表,每个都复制两次,得到temp = [[1], [1]],然后target被赋值为这个新列表 - 给每个子列表添加元素:遍历
target,依次把add[0](2)、add[1](4)追加到子列表里,此时target变成[[1,2], [1,4]] add翻倍:变成[2,4,2,4],count变为1
第二次循环(count=1)
- 再次把
target翻倍:遍历[[1,2], [1,4]],每个子列表复制两次,得到temp = [[1,2], [1,2], [1,4], [1,4]],赋值给target - 给每个子列表添加元素:依次把
add[0](2)、add[1](4)、add[2](2)、add[3](4)追加进去,target变成[[1,2,2], [1,2,4], [1,4,2], [1,4,4]] add翻倍成[2,4,2,4,2,4,2,4],count变为2,外层循环结束
为什么去掉while循环也能运行?
因为外层的while count < 2只是把“翻倍target→添加元素→翻倍add”这个流程重复了两次。如果你手动把这两次流程写出来,不用while循环,代码确实能正常运行,比如:
target = [[1],] add = [2,4] # 第一次执行流程 temp = [] for i in target: temp += [i, i] target = temp[:] print('before', target) idx = 0 while idx < len(target): target[idx].append(add[idx]) idx += 1 print('after', target) add += add # 第二次执行流程 temp = [] for i in target: temp += [i, i] target = temp[:] print('before', target) idx = 0 while idx < len(target): target[idx].append(add[idx]) idx += 1 print('after', target) add += add
这段代码和你原来的while版本运行结果完全一致,所以你说的“没有while循环也能正常运行”是完全正确的——while只是帮你简化了重复代码的书写而已。
另外,这里的内层while循环(idx < len(target))其实可以换成更Pythonic的for循环,比如用enumerate来同时获取索引和子列表:
for idx, sub_list in enumerate(target): sub_list.append(add[idx])
这样代码会更简洁易读~
内容的提问来源于stack exchange,提问作者jxie0755
相关产品推荐
相关产品推荐

