【发布时间】:2020-08-04 15:53:09
【问题描述】:
我定义了一个改变列表的函数(基本上将最后一项移动到列表的开头),然后我尝试用这个函数制作一个二维列表。
这里有一些代码:
prevRow = ["blue", "yellow", "red", "black", "white"]
def nextRow():
prevRow.insert((0, prevRow.pop()))
print(prevRow)
return prevRow
tablePreset = [["blue", "yellow", "red", "black", "white"], nextRow(), nextRow(), nextRow(), nextRow()]
print(tablePreset)
prevRow = ["blue", "yellow", "red", "black", "white"]
tablePreset = [["blue", "yellow", "red", "black", "white"]]
def nextRow():
prevRow.insert((0, prevRow.pop()))
print(prevRow)
return prevRow
for _ in range(4):
tablePreset.append(nextRow())
print(tablePreset)
在这两种情况下我都得到了
['white', 'blue', 'yellow', 'red', 'black']
['black', 'white', 'blue', 'yellow', 'red']
['red', 'black', 'white', 'blue', 'yellow']
['yellow', 'red', 'black', 'white', 'blue']
[['blue', 'yellow', 'red', 'black', 'white'], ['yellow', 'red', 'black', 'white', 'blue'], ['yellow', 'red', 'black', 'white', 'blue'], ['yellow', 'red', 'black', 'white', 'blue'], ['yellow', 'red', 'black', 'white', 'blue']]
我不知道为什么,但即使我调用了 4 次函数,列表中的每个返回值都与最后一个值相同(函数内的打印用于调试目的)。
如果有人帮助我,我会非常高兴:)
【问题讨论】:
标签: python-3.x list multidimensional-array