gpt4 book ai didi

python - For循环不更新列表

转载 作者:行者123 更新时间:2023-12-04 03:38:14 24 4
gpt4 key购买 nike

主要代码:

for i in Pool:
print(i)
while(i[0] != 1):
print('i is ' + str(i))
i=rotate(i)
print('after rotate i is ' + str(i))
print(Pool)

旋转函数:

def rotate(a):
a= a[1:]+a[:1]
return a

结果:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
i is [2, 1, 3]
after rotate i is [1, 3, 2]
[2, 3, 1]
i is [2, 3, 1]
after rotate i is [3, 1, 2]
i is [3, 1, 2]
after rotate i is [1, 2, 3]
[3, 1, 2]
i is [3, 1, 2]
after rotate i is [1, 2, 3]
[3, 2, 1]
i is [3, 2, 1]
after rotate i is [2, 1, 3]
i is [2, 1, 3]
after rotate i is [1, 3, 2]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

根据这段代码,Pool = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

我可以看到我的轮换函数起作用并将 3,2,1 轮换为 2,1,3 但它没有更新到池中。我想要的结果是 [[1, 2, 3], [1, 3, 2], [1, 3, 2], [1, 2, 3], [1, 2, 3], [1, 3 , 2]]

最佳答案

您正在创建一个新列表,而不是原地轮换。

要原地旋转列表,请使用 a[:] = a[1:] + a[:1];然后您还可以省略 return(省略它可能是更好的样式)。

def rotate(a):
""" Rotate the list in-place """
a[:] = a[1:] + a[:1]

然后您可以在不使用返回值(将为 None)的情况下调用此函数:

for i in Pool:
while i[0] != 1:
rotate(i)

关于python - For循环不更新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66540239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com