简体   繁体   English

如何将整个矩阵作为Python的输入?

[英]How to take a whole matrix as a input in Python?

I want to take a whole matrix as an input in Python and store it in a dataframe. Pandas can do it automatically with read_csv function but it requires a CSV file.我想将整个矩阵作为 Python 中的输入并将其存储在 dataframe 中。Pandas 可以使用 read_csv function 自动完成,但它需要一个 CSV 文件。 I want to input/copy-paste a matrix directly at the input, without specifying its height or width and intelligently separate the rows and columns using Line Break as a separator and store it in a dataframe. Looked up the read_csv source code but it all went over my head.我想直接在输入中输入/复制粘贴一个矩阵,而不指定它的高度或宽度,并使用换行符作为分隔符智能地分隔行和列,并将其存储在 dataframe 中。查找 read_csv 源代码,但这一切越过我的头。 your help will be appreciated.您的帮助将不胜感激。

What's a Matrix: Basically a Mathematical table or Dataframe which Looks something like this... matrix in a notepad什么是矩阵:基本上是一个数学表或 Dataframe,它看起来像这样......记事本中的矩阵

What I have Come up with up until now is the same old thingy:到目前为止,我想出的是同样的老东西:

 '''
inp=input("Enter the Size of Your Matrix: ")
inp=inp.translate({ord(i): None for i in 'x ,'})
w=int(inp[0])
h=int(inp[1])
        
print(w, "and", h)

df=pd.DataFrame()

for x in range(h):
    for i in range(w):
        m=input("Enter Data into Matrix at Position")
        print(x,",",i)
        df.loc[x,i]=m
        
print(df)

''' What I want to do is if I have a matrix copied like like the one shown above, I can use it directly as a input to store in a dataframe, and I want the code to be intelligent enough to break up the lines automatically wherever there is a line Break. ''' 我想要做的是,如果我有一个像上面所示那样复制的矩阵,我可以直接将它用作输入以存储在 dataframe 中,并且我希望代码足够智能以分解这些行在有换行的地方自动换行。

You can use sys.stdin.read() to read well... from stdin.您可以使用sys.stdin.read()来很好地阅读……来自标准输入。

import sys

matrix = sys.stdin.read()

matrix = matrix.strip().split('\n')
matrix = [row.split(' ') for row in matrix]

Now you get something like [['2', '3', '4'], ['6', '7', '8'], ['4', '1', '1']] and you can convert it to your desired format.现在你得到类似[['2', '3', '4'], ['6', '7', '8'], ['4', '1', '1']]和你可以将其转换为您想要的格式。

Note that once you have pasted your matrix, you still need to tell the system to stop reading.请注意,一旦您粘贴了矩阵,您仍然需要告诉系统停止读取。 In Windows you can do it with Ctrl + Z followed by Enter .在 Windows 中,您可以使用Ctrl + Z后跟Enter来完成。 In Linux with Ctrl + D (no enter afterwards).在 Linux 中使用Ctrl + D (之后没有输入)。

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

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