2014-01-15 23 views
0

我需要以非常特定的格式生成輸出,並且正整數必須在它們前面有加號。我使用numpy的陣列,並試圖東西,如:如何在Python中的int之前添加加號?

if(int(P[pnt])>0): 
     P[pnt] += np.insert(P[pnt-1],0,"+") 

但它從來沒有添加作爲加數字的一部分,而是作爲一個不同的實例..

我也試圖將其保存在不同的文件,然後從那裏(使用re.sub()等...),但沒有運氣:(修改

我的輸出是這樣的:

(+1 2 -4 +5 -3) 
(+1 2 3 -5 4) 
(+1 2 3 -4 5) 
(+1 2 3 4 5) 

,應該是這樣的:

(+1 +2 -4 +5 -3) 
(+1 +2 +3 -5 +4) 
(+1 +2 +3 -4 +5) 
(+1 +2 +3 +4 +5) 

如果必要的話,我可以共享整個代碼...

謝謝! :)

回答

6

使用.format()Python Format mini-language。你想要+標誌選項。

'{:+}'.format(3) # "+3" 
'{:+}'.format(-3) # "-3" 

可以去堅果:

a = numpy.array([1, 2, -4, 5, -3]) 
print '(' + ' '.join('{:+}'.format(n) for n in a)) + ')' 
# (+1 +2 -4 +5 -3) 
+0

非常感謝你!但是當我嘗試,我得到這個錯誤:ValueError:簽名不允許在字符串格式說明符。如果我嘗試將我的數組變量作爲整數進行投射,它根本就不會做任何事情。我想這是因爲我正在從文件中讀取這些值,它認爲這些值是字符串?或者可能是因爲「+」和「 - 」在我的輸入中? – FairyDuster

+0

是的,你可能有dtypes作爲字符串。所以你需要轉換數組的dtype。這應該這樣做:'a = a.astype(int)',或者你可以在創建數組時設置dtype。 – M4rtini

+0

工作!非常感謝! :)))) – FairyDuster

0

我不是一個環境,我可以測試它,但numpy.insert應沿軸插入對象,在一個前追加一個新的索引/值你選擇。

在您的條件語句中,實際結果可能會將P [pnt]設置爲'+'+ str(P [pnt])。你最後在尋找一串字符串,是的?

2

添加到尼克T的答案:
您可以編輯numpy的打印選項,所以每當您打印一個numpy陣列格式化將發生。

In [191]: np.set_printoptions(formatter={'all':lambda x: '{:+}'.format(x)}) 

In [198]: np.random.random_integers(-5,5,(5,5)) 
Out[198]: 
array([[+2, +2, +2, -4, +0], 
     [-2, -1, +3, +5, -1], 
     [-5, -2, -1, -3, +4], 
     [+1, +3, -5, +3, -4], 
     [+2, -1, +2, +5, +5]]) 

'all'定義該格式應該使用什麼類型。 set_printoptions的文檔字符串將告訴您可以在那裏設置更具體的格式。

 - 'bool' 
    - 'int' 
    - 'timedelta' : a `numpy.timedelta64` 
    - 'datetime' : a `numpy.datetime64` 
    - 'float' 
    - 'longfloat' : 128-bit floats 
    - 'complexfloat' 
    - 'longcomplexfloat' : composed of two 128-bit floats 
    - 'numpy_str' : types `numpy.string_` and `numpy.unicode_` 
    - 'str' : all other strings 

Other keys that can be used to set a group of types at once are:: 

    - 'all' : sets all types 
    - 'int_kind' : sets 'int' 
    - 'float_kind' : sets 'float' and 'longfloat' 
    - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' 
    - 'str_kind' : sets 'str' and 'numpystr' 
+0

謝謝!這是一個很好的提示!不幸的是,就像我上面提到的,我不斷收到這個錯誤:ValueError:在字符串格式說明符中不允許簽名。有什麼建議麼? – FairyDuster

相關問題