2015-03-13 45 views
1

我有2個python列表,我想使用np.savetxt()並排保存。在savetxt中結合python列表

我曾嘗試:

np.savetxt('./filename.txt',np.hstack([list1,list2]),fmt=['%f','%f']) 

,但我得到的錯誤信息

raise AttributeError('fmt has wrong shape. %s' % str(fmt)) 
AttributeError: fmt has wrong shape. ['%f', '%f'] 

我不知道這是否是相關的,但名單是decimal.Decimal格式。

我在做什麼錯誤?


編輯:我原本說「vstack」,但我的意思是「hstack」。

+1

爲什麼你試圖通過一個數組到'fmt'關鍵字參數? – cel 2015-03-13 15:16:43

+0

我試圖按照這裏的解決方案http://stackoverflow.com/questions/16317840/savetxt-two-columns-in-python-numpy – user1551817 2015-03-13 15:20:08

+1

@ user1551817該示例的工作原理是因爲傳遞給格式的列表與一個大小相同數據數組的行。 – Carsten 2015-03-13 15:22:29

回答

1

一個值就傳遞給fmt,像這樣:

np.savetxt('./filename.txt',np.vstack([list1,list2]),fmt='%f') 

例子:

import decimal, numpy as np 
a = np.array([decimal.Decimal("1.0"), 
       decimal.Decimal("2.0"), 
       decimal.Decimal("3.0")], 
      dtype=np.dtype(decimal.Decimal)) 
b = a + 1 
np.savetxt('./filename.txt',np.vstack([a, b]),fmt='%f') 

生成的文件是這樣的:

1.000000 2.000000 3.000000 
2.000000 3.000000 4.000000