2013-01-02 63 views
0

我使用Python進行編程。 這是我的代碼:使用numpy.savetxt後的問題

def data_exp(nr, nc): 
    data=numpy.zeros((nr, nc)) 
    print data 
    for i in range(0, nr): 
     for j in range (0, nc): 
      data[i, j]=input('Insert values: ') 
    numpy.savetxt(str(input('Insert the name of the file (ex: "a.txt"): ')), data) 
    return data 

的問題是,這個方案沒有返回值!我忽略了numpy.savetxt後的所有內容!有人能告訴我如何克服這個問題嗎?

回答

2

你的問題是不適當使用inputinput相當於eval(raw_input())。調用eval()將嘗試和評估您在程序中的全局變量和本地變量中作爲python源代碼輸入的文本,這顯然不希望您在此情況下執行此操作。我很驚訝你沒有得到一個運行時錯誤報告你輸入的字符串沒有被定義。

嘗試使用raw_input代替:

def data_exp(nr, nc): 
    data=numpy.zeros((nr, nc)) 
    print data 
    for i in range(0, nr): 
     for j in range (0, nc): 
      data[i, j]=input('Insert values: ') 
    numpy.savetxt(str(raw_input('Insert the name of the file (ex: "a.txt"): ')), data) 
    return data 

編輯:

這裏是上面的代碼,在IPython中會爲我工作。如果你不能得到它的工作,別的東西是錯誤的:

In [7]: data_exp(2,2) 
[[ 0. 0.] 
[ 0. 0.]] 
Insert values: 1 
Insert values: 2 
Insert values: 3 
Insert values: 4 
Insert the name of the file (ex: "a.txt"): a.txt 
Out[7]: 
array([[ 1., 2.], 
     [ 3., 4.]]) 

In [8]: data_exp?? 
Type:  function 
Base Class: <type 'function'> 
String Form: <function data_exp at 0x2ad3070> 
Namespace: Interactive 
File:  /Users/talonmies/data_exp.py 
Definition: data_exp(nr, nc) 
Source: 
def data_exp(nr, nc): 
    data=numpy.zeros((nr, nc)) 
    print data 
    for i in range(0, nr): 
     for j in range (0, nc): 
      data[i, j]=input('Insert values: ') 
    numpy.savetxt(str(raw_input('Insert the name of the file (ex: "a.txt"): ')), data) 
    return data 

In [9]: _ip.system("cat a.txt") 
1.000000000000000000e+00 2.000000000000000000e+00 
3.000000000000000000e+00 4.000000000000000000e+00 
+0

我試過但仍對numpy.savetxt後什麼都不做:一切,我問它是被忽略後做! – Ale

+0

@Ale:我發佈的內容如您所期望的那樣,請參閱我的修改。 – talonmies

+0

好!看來我有一些python的問題...我決定這樣做: def data_exp(nr,nc): data = np.zeros((nr,nc)) 我在範圍內(0,nr): 在範圍Ĵ(0,NC): 數據[I,J] =的raw_input( '插入值:') 打印數據 打印 '要保存陣列位節省(數據)和插入名' 返回數據 def save(data): np.savetxt(str(input('插入列表名稱(例如:a.txt):')),數據) – Ale