Was Sie mit einer Schleife tun würde mit range
genauso gut funktionieren. Keine Notwendigkeit, numpy
zu verwenden.
Aber wenn dies eine Übung zum Lernen numpy
ist, würde ich einen anderen Ansatz vorschlagen.
Erstellen Sie ein Array direkt aus den Bereichen. //
ist eine Ganzzahldivision.
In [99]: A=2*np.arange(4)[:,None]//np.arange(1,4)
In [100]: A
Out[100]:
array([[0, 0, 0],
[2, 1, 0],
[4, 2, 1],
[6, 3, 2]], dtype=int32)
Sie über mehrere Spalten mit einem Array-Verfahren summieren können:
In [101]: A.sum(axis=1)
Out[101]: array([ 0, 3, 7, 11], dtype=int32)
Um ein schönes Format zu bekommen, ohne Klammern und solche, erstellen eine Reihe Formatierung string:
In [102]: fmt = '%d + %d + %d = %d'
In [103]: for row in A:
print(fmt%(tuple(row)+(row.sum(),)))
.....:
0 + 0 + 0 = 0
2 + 1 + 0 = 3
4 + 2 + 1 = 7
6 + 3 + 2 = 11
(Die Funktion Druckform ist normal in Python3, und in 2.7)
Ich könnte eine Variation verwendet haben um dies in eine Datei über np.savetxt
zu schreiben.
In [104]: A.sum(axis=1,keepdims=True) # sum in column array shape
Out[104]:
array([[ 0],
[ 3],
[ 7],
[11]], dtype=int32)
In [105]: A1 = np.concatenate((A, A.sum(axis=1,keepdims=True)),axis=1)
In [106]: A1 # the values and sum in one array
Out[106]:
array([[ 0, 0, 0, 0],
[ 2, 1, 0, 3],
[ 4, 2, 1, 7],
[ 6, 3, 2, 11]], dtype=int32)
In [107]: np.savetxt('test.txt',A1,fmt=fmt)
In [108]: cat test.txt # look at the resulting file
0 + 0 + 0 = 0
2 + 1 + 0 = 3
4 + 2 + 1 = 7
6 + 3 + 2 = 11
A python2.7 Version ohne numpy:
>>> for m in range(4):
... row = [2*m/n for n in range(1,4)]
... fmt = '%d + %d + %d = %d'
... print fmt%(tuple(row)+(sum(row),))
...
0 + 0 + 0 = 0
2 + 1 + 0 = 3
4 + 2 + 1 = 7
6 + 3 + 2 = 11
Ist das Hausaufgaben? – Merlin