【问题标题】:While loop to modify multiple elements in a nested loopWhile循环修改嵌套循环中的多个元素
【发布时间】:2015-04-07 11:58:45
【问题描述】:

我正在尝试使用 while 循环 getInput(myList) 更改此嵌套列表游戏板中的多个元素,但是当我输入“q”时循环不会停止

def firstBoard():
    rows = int(input("Please enter the number of rows: "))
    col = int(input("Please enter the number of columns: "))
    myList = [[0]*col for i in range(rows)]
    return myList
def getInput(myList):
    rows = input("Enter the row or 'q': ")
    col = input("enter the column: ")
    while rows != "q":
        rows = input("Enter the row or 'q': ")
        col = input("Enter the column: ")
        myList[int(rows)-1][int(col)-1] = "X"

    return myList

def printBoard(myList):
    for n in myList:
        for s in n:
            print(s, end= " ")

def main():
    myList = firstBoard()
    myList = getInput(myList)
    printBoard(myList)
main()

例如,如果我希望我的输出结果如下:

X 0 0 0 0
0 X 0 0 0
0 0 X 0 0
0 0 0 0 0
0 0 0 0 0

【问题讨论】:

    标签: python-3.x while-loop


    【解决方案1】:

    当输入 'q' 时,您不会立即退出循环,而是尝试强制转换为 int('q'),这会引发异常。您可以将其替换为:

    def getInput(myList):
        while True:
            rows = input("Enter the row or 'q': ")
            if rows == 'q':
                break
            col = input("Enter the column: ")
            myList[int(rows)-1][int(col)-1] = "X"
        return myList
    

    这也解决了您忽略第一个条目的事实。
    您可能还需要在 printBoard() 中进行额外打印,否则整个电路板将打印在一行上。

    【讨论】:

      猜你喜欢
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 2022-10-12
      • 1970-01-01
      相关资源
      最近更新 更多