2016-06-08 510 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