我正在学习Python,并且一直在尝试制作双端队列。但是,我得到的输出不正确,我不确定为什么。我的代码如下:
p = [2, 1], [1, 1]
init_q= deque()
init_q.append(p)
for i in range(len(p)):
for j in range(len(p[i])):
temp = p[i][j]
p[i][j] = 0
init_q.append(p)
p[i][j] = temp
while init_q:
print init_q.pop()
在此代码中,我接受一个列表,然后我想创建一个包含5个列表的队列,其中4个列表在不同位置的位置为0,我想要的结果是:
([2, 1], [1, 1])
([0, 1], [1, 1])
([2, 0], [1, 1])
([2, 1], [0, 1])
([2, 1], [1, 0])
但是,我得到的结果是:
([2, 1], [1, 1])
([2, 1], [1, 1])
([2, 1], [1, 1])
([2, 1], [1, 1])
([2, 1], [1, 1])
最佳答案
我通过简化您的代码在Python Tutor上创建了visualization。四处逛逛,您可以轻松地看到正在发生的事情。
对代码进行单行更改可以解决此问题。
init_q.append(map(list, p)) # Initialize a new list from p's element lists
这是使用上述更改的visualization。
关于Python双端队列范围?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14189458/