2016-06-08 237 views
0

我对Python很陌生,我试图翻译Matlab代码。我试图编写一个程序,以用户从红外培训​​光谱上传或输入数据开始,然后将程序附加到数组或矩阵中。但我不能肯定我这样做是正确的如何让用户在Python上输入矩阵?

# 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“,程序运行良好。如何让它将每个输入识别为列表中的单独项目?

+1

只是基于用户的备注 - 不问任何人用手将矩阵放入stdin中。这不是一个有用的方法。只需要以某种通用格式请求一个包含矩阵的文件的路径,例如.csv – lejlot

+1

“*我一直收到错误*”是我们无法帮助您的足够信息。 –

+0

@lejlot这可能是一个非常愚蠢的问题,但你怎么做? –

回答

1

到目前为止,您的代码还行,但如果您使用的是Python 2.7,则btrain = [input("Input btrain as a list of values separated by commas.")]将最终成为单个字符串的列表或您的值的元组列表的列表。正确的方式做这将是

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

拆分(分隔符)给出了在这种情况下,一些分隔符分裂的所有值的列表“”

+0

谢谢,它修复了它。当我将它命令到 print(btrain_multidimensional_array) Traceback(最近调用最后一个): 文件“C:\ Users \ Cynthia \ Documents \ Lodder Lab \ Spectral Analysis \ Supa Fly.py” ,第24行,在 print(btrain_multidimensional_array) NameError:名称'btrain_multidimensional_array'未定义 任何想法为什么我命令它返回的对象不存在? –

+0

这个错误来自于np.reshape()不返回任何东西。它只是重塑现有的数组,所以你不需要分配一个新的变量。你的其他错误也应该消失。 – RainbowRevenge