【问题标题】:Input a single time instead of asking multiple time输入一次而不是多次询问
【发布时间】:2021-05-24 14:39:12
【问题描述】:

我被这段代码卡住了,它要求用户输入整数(9x9),然后程序会根据用户的输入(二维列表)获取坐标。代码有效,但我只是卡在输入过程中。

它不是询问单次输入,而是询问“输入一个数组” 9 次,例如我希望输出看起来像这样:

Enter an array:
359716482
867345912
413928675
398574126
546281739
172639548
984163257
621857394
735492861

但是我的代码给了我这个:

Enter an array:
359716482
Enter an array:
867345912
Enter an array:
413928675
Enter an array:
398574126
Enter an array:
546281739
Enter an array:
172639548
Enter an array:
984163257
Enter an array:
621857394
Enter an array:
735492861
# Goal1: user to input integer values and query a 2-dimensional array of size 9x9.
# Goal2: program should then ask the user for a pair of coordinates, (x, y), separated by a space and return the value at the position specified by the given coordinates

def gridformation(grid):                      # Creating grid using lists by asking for user input 9 times (9x9)
  for i in range(9):
    array = input("Enter an array: \n")
    grid.append(array)
  return grid

def coordinates(NumGrid):                     # Function to obtain coordinates
  coordinate = input("Enter coordinates: \n")
  split = coordinate.split(" ")               # Split coordinates by spaces

  x = int(split[0])                           # coordinate x is the first one
  y = int(split[1])                           # coordinate y is the second one

  while x != -1 or y != -1:                   # Continous while loop unless user types in -1 that stops the process
    value = NumGrid[x][y]                     # 2-d list to obtain respective number
    print("Value =", value)
    coord = input("Enter coordinates: \n")    # to keep asking for coordinate input

    splited = coord.split(" ")

    x = int(splited[0])
    y = int(splited[1])
  
  print("DONE")

def main():                                   # main function that initiates the program in order
  grid = []
  NumGrid = gridformation(grid)
  coordinates(NumGrid)


if __name__ == '__main__':
  main()

【问题讨论】:

  • 所以问题只出在提示符上?
  • 是的,但我看到了你的回答 :) 非常感谢它成功了!

标签: python arrays input


【解决方案1】:

因为你有

for i in range(9):
    array = input("Enter an array: \n")
    grid.append(array)

改成:

print("Enter an array:")
for i in range(9):
    array = input()
    grid.append(array)

【讨论】:

    【解决方案2】:

    您必须编写数据条目以匹配您想要的输入序列。如果您希望提示只打印一次,则只打印一次。你把它放在循环中,每次迭代都会打印出来。而是:

    print("Enter an array, one line at a time:")
    for i in range(9):
        line = input()
        grid.append(line)
    return grid
    

    【讨论】:

      猜你喜欢
      • 2013-05-26
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多