繁体   English   中英

您如何要求用户在Python上输入矩阵?

[英]How do you ask a user to input a matrix on Python?

我对Python很陌生,并且正在尝试翻译Matlab代码。 我正在尝试编写一个程序,该程序首先是用户从IR训练频谱上载或输入他们的数据,然后将该程序附加到数组或矩阵中。 但是我不确定自己是否做得正确(特别是因为我不断收到错误!)

# Requires numpy and math.

# Import necessary modules.
import numpy as np
import math

# Get data for the training spectra as a list.
# Then turn that list into a numpy array given the user's input of how many
# rows and columns there should be.
# (An alternate way to do this would be to have users input it with commas and
# semi-colons.)
# btrain_matrix returns the array.
def btrain_matrix():
    btrain = [input("Input btrain as a list of values separated by commas.")]
    btrain_row_number = int(input("How many rows should there be in this matrix? \n i.e., how many training samples were there?"))
    btrain_column_number = int(input("How many columns should there be in this matrix? \n i.e., how many peaks were trained?"))

    btrain_array=np.array(btrain)
    btrain_multidimensional_array = btrain_array.reshape(btrain_row_number,btrain_column_number)

    print(btrain_multidimensional_array)
    return (btrain_multidimensional_array)

btrain_matrix()
btrain_row_number = input("Please re-enter the number of rows in btrain.")

# Insert a sequence to call btrain_matrix here

我得到的错误是这样的:

Input btrain as a list of values separated by commas.1,2,3
How many rows should there be in this matrix? 
 i.e., how many training samples were there?1
How many columns should there be in this matrix? 
 i.e., how many peaks were trained?3
Traceback (most recent call last):
  File "C:\Users\Cynthia\Documents\Lodder Lab\Spectral Analysis\Supa Fly.py", line 24, in <module>
    btrain_matrix()
  File "C:\Users\Cynthia\Documents\Lodder Lab\Spectral Analysis\Supa Fly.py", line 19, in btrain_matrix
    btrain_multidimensional_array = btrain_array.reshape(btrain_row_number,btrain_column_number)
ValueError: total size of new array must be unchanged

如果我输入“ 1,2,3”和“ 1”,“ 1”,则程序运行正常。 我如何才能将这些输入中的每一个识别为列表中的单独项目?

到目前为止,您的代码还可以,但是btrain = [input("Input btrain as a list of values separated by commas.")]最终将是单个字符串的列表或值的元组的列表在python 2.7上。 正确的方法是

btrain = input("Input btrain as a list of values separated by commas.").split(",")

split(delimiter)给出在这种情况下在某个定界符处拆分的所有值的列表。

暂无
暂无

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

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