简体   繁体   English

如何从用户输入中捕获矩阵并在用户输入时将其打印出来?

[英]How do I capture a matrix from a user input and print it out as the user input it?

I'm messing around with numpy trying to create a 3x3 matrix.我正在尝试使用 numpy 创建一个 3x3 矩阵。 I want to capture the matrix input via user input and then print the matrix out as the user entered it.我想通过用户输入捕获矩阵输入,然后在用户输入时打印出矩阵。

Here's what I have now, it throws a这就是我现在拥有的,它抛出一个

ValueError: invalid literal for int() with base 10: 

when I run it and I have no idea why.当我运行它时,我不知道为什么。 I'm not entering the letter "a" anywhere, only numbers.我没有在任何地方输入字母“a”,只输入数字。

def matrix():
    row = int(3)
    column = int(3)
    matrix_input = []
    print("Enter the entries in a single line (separated by space): ")
    for i in range(row):  # A for loop for row entries
        entries = []
        for j in range(column):  # A for loop for column entries
            entries.append(int(input()))
        matrix_input.append(entries)

    # matrix_input = np.array(entries).reshape(row, column)
    print(matrix_input)

The goal is to get the user to input 3 numbers on three separate lines.目标是让用户在三个单独的行上输入 3 个数字。 Example:例子:

130
304
603

The program would then type this back out exactly as the user entered it and in the same format.然后,该程序将完全按照用户输入的格式并以相同的格式将其重新输入。

130
304
603

Any guidance would be much appreciated.任何指导将不胜感激。 Thanks谢谢

Right now, your code asks for each element seperately.现在,您的代码分别要求每个元素。 If you enter numbers until it ends itself like如果你输入数字直到它结束自己像

111
222
333
444
555
666
777
888
999

the program will return程序将返回

[[111, 222, 333], [444, 555, 666], [777, 888, 999]]

This happens because the input() is inside the inner most loop, and is consequently called 9 times.发生这种情况是因为input()位于最内部的循环内,因此被调用了 9 次。

So if you want to enter the values separated by space as indicated, you could use list comprehension to convert this to a list of numbers:因此,如果您想输入由空格分隔的值,您可以使用列表理解将其转换为数字列表:

row = int(3)
matrix_input = []
print("Enter the entries in a single line (separated by space): ")
for i in range(row):  # A for loop for row entries
    matrix_input.append([int(k) for k in input().split(' ')])

for out in matrix_input:
    print('{0} {1} {2}'.format(*out))

This will ask for three entries, which are split along the spaces and converted to integer.这将要求三个条目,它们沿空格分开并转换为整数。 If you want floats, you could use float(k) instead of int(k) .如果你想要浮点数,你可以使用float(k)而不是int(k) The print command uses unpacking and the fact that the for ... in returns the rows.打印命令使用解包以及for ... in返回行的事实。

Alternatively, you could use ' '.join() , which is more flexible:或者,您可以使用更灵活的' '.join()

for out in matrix_input:
    print(' '.join([str(el) for el in out]))

This is in fact the inverse operation of the construction of the matrix.这实际上是矩阵构造的逆运算。

def matrix(): 
    row = int(3)
    column = int(3)
    matrix_input = []
    print("Enter the entries in a single line (separated by space): ")

    for i in range(row):  # A for loop for row entries
        ints =input()

        entries = []

        for a in ints:
          entries.append(int(a))
        matrix_input.append(entries)

    for ele in matrix_input:
      for d in ele:
        print(d,end='')
      print('')

matrix()

Input:输入:

Enter the entries in a single line (separated by space): 
130
304
603

Output:输出:

130
304
603

The problem is that you're trying to convert an entire string (the input with spaces between each int) to an integer.问题是您试图将整个字符串(每个 int 之间有空格的输入)转换为整数。

Instead you need to split out the input.相反,您需要拆分输入。 See below:见下文:

def matrix():
    row = int(3)
    column = int(3)
    matrix_input = []
    print("Enter the entries in a single line (separated by space): ")
    
    input_str = input()
    
    entries = []
    entries.extend([int(x) for x in input_str.split(' ')])
    
    for item in entries:
        print(item)

This does the trick.这就是诀窍。

def matrix():
    row = int(3)
    column = int(3)
    matrix_input = []
    print("Enter the entries in a single line (separated by space): ")
    for i in range(row):  # A for loop for row entries
        # ints = input().split()
        while True:
            ints = input().split()
            if len(ints) == 3:
                break
            print("Invalid Input Received")
            print("Enter the entries in a single line (separated by space): ")
        entries = []
        for a in ints:
            entries.append(int(a))
        matrix_input.append(entries)
    print("Output")
    for ele in matrix_input:
        for d in ele:
            print(d, end=' ')
        print('')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM