【问题标题】:How to modify matrix with user inputs in while loop, and break when user inputs string?如何在while循环中使用用户输入修改矩阵,并在用户输入字符串时中断?
【发布时间】:2019-08-14 22:23:18
【问题描述】:

我正在尝试编写一个程序,该程序在一个while循环中修改给定用户输入的矩阵,并继续接收输入,直到用户输入一个字符串。

这基本上是我的最终目标:

for a matrix i=[[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]]
user input:
2
3
3
3
t

for user inputs, the first integer specifies the row, and the next one following it specifies the column.

expected output: i=[[0,0,0,0,0], [0,0,1,0,0], [0,0,1,0,0], [0,0,0,0,0]]

我尝试了几种方法,但仍然没有得到我想要的:

while True:
    x=input()   
    y=input()
    if type(y)==int and type(x)==int:
     i[x][y]=1
    else:
      break
print(i)

This outputs original configuartion [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]]

我也试过这个:

while True:
    x=input()
    y=int(input())
    i[x][y]=1
    if x=="t":
        break

print(i)

outputs TypeError: list indices must be integers or slices, not str

【问题讨论】:

  • if type(y)==int 总是失败,因为用户输入总是一个字符串。您需要try/except 来查看输入字符串是否可以转换
  • 带有try/except 这个评论意义不大,但你也应该使用isinstance 来检查类型

标签: python python-3.x loops input while-loop


【解决方案1】:

input() return a 'str' so i[x] raises 'list indices must be integers or slices, not str'

【讨论】:

  • 那么他们的方法应该是什么样的?
  • @roganjosh - 我不确定我是否理解你的问题。请解释一下。
  • 好吧,如果您扭转局面,这是您问题的答案,您将如何实施它?它没有说明实际的方法应该是什么
  • 知道了..我认为解决方案很明显 - 尝试转换为 int,如果失败,请用户再次插入输入。
  • 解决方案对您来说可能很明显,但如果您设身处地为 OP 着想,则不一定 :)
【解决方案2】:

您在这里面临几个问题。

首先,您必须将输入转换为列表索引,但前提是第一个输入 (x) 不是“t”。 我在循环的开头添加了这个比较,所以我们终止了循环,甚至不用理会 y。

然后,输入 x 和 y 都转换为 int(使用 int()),我们从它们中减去 1,因为我知道用户必须输入“自然”矩阵索引(从 1 开始),而不是 python 索引(从零开始)。

mat = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

while True:
    x = input()
    if x is 't':
        break;
    else:
        xi = int(x) - 1
        yi = int(input()) - 1

    mat[xi][yi] = 1

print(mat)

请注意,实际上会在此处进行进一步的输入检查,但我将其保持在最低限度。

输入检查功能的示例如下:

def check_x(x_local):
    if len(x_local) is not 1:
        raise ValueError()
    return x_local

如果输入的输入不是单个字符,这将触发异常。 然后你可以像这样在你的主程序中调用它:

x = check_x(input())

【讨论】:

    【解决方案3】:

    这可以解决问题 :) 在索引期间而不是在 input() 期间进行一点重新排序和类型转换,还修复了许多其他问题

    i=[[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]]
    
    
    while True:
    
        x=input()
        y=input()
    
        """ As we're unsure when we'd like to break, lets assume t could be in x or y """
        if x == "t" or y == "t":
            break
        """ Convert both inputs to ints """
        else:
          i[int(x)][int(y)]=1
    
    print(i)
    

    【讨论】:

      猜你喜欢
      • 2015-07-03
      • 2017-01-27
      • 1970-01-01
      • 2018-07-25
      • 2014-01-01
      • 2019-04-20
      • 2013-11-16
      • 2020-02-15
      • 2016-08-12
      相关资源
      最近更新 更多