Python 3.x 更改嵌套列表中的一个元素
我有这个代码来制作一个游戏板并改变其中一个元素Python 3.x 更改嵌套列表中的一个元素,python-3.x,Python 3.x,我有这个代码来制作一个游戏板并改变其中一个元素 def firstBoard(): rows = int(input("Please enter the number of rows: ")) col = int(input("Please enter the number of columns: ")) myList = [[0]*col]*rows return myList def getInput(myList): rows = int(input
def firstBoard():
rows = int(input("Please enter the number of rows: "))
col = int(input("Please enter the number of columns: "))
myList = [[0]*col]*rows
return myList
def getInput(myList):
rows = int(input("Enter the row or 'q': "))
col = int(input("enter the column: "))
myList[rows-1][col-1] = "X"
return myList
def printBoard(myList):
for n in myList:
for s in n:
print(s, end= " ")
print()
def main():
myList = firstBoard()
myList = getInput(myList)
print(printBoard(myList))
main()
我想要游戏板的输出:
Please enter the number of rows: 5
Please enter the number of columns: 5
Enter the row or 'q': 1
Enter the column: 1
X 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
但我得到的是:
X 0 0 0 0
X 0 0 0 0
X 0 0 0 0
X 0 0 0 0
X 0 0 0 0
None
你知道如何解决这个问题,摆脱“底部没有”吗 将评论作为答案发布
在第四行中,请改为:
myList = [[0]*col for i in range(rows)]
您看到的行为是由于您在每一行上创建了相同的列表
由于您已经在printBoard(…)
中获得了打印电路板的代码,请删除对print()
的最后一个调用,例如:main()
中的最后一行应该是:
printBoard(myList)
在第四行中,请改为:
myList=[[0]*col代表范围内的i(行)]
关于这一点,在某个地方有一个很好的答案。这很有效!你知道如何摆脱“无”吗?我知道我必须使用return语句而不是print,但idk如何返回语句使其看起来像我也需要它。因为您已经在printBoard(…)
中获得了打印电路板的代码,请删除对print()
的最后调用,例如:main()
中的最后一行应该是:printBoard(myList)
是否有人可以将这些评论中的一条添加到回答中以结束此问题,或者@AlexRochford是否可以删除此问题。。。