@John是正確的關於如何使用返回值從numpy.append
,因爲它不會修改原始數組。然而,有一個與你的預期輸出的一個問題:
[[0 1 0 0]
[1 1 0 1]
[0. 0. 0. 0.]
5]
是不是因爲兩個原因,一個可能的numpy的數組:一個是一些元素是整數的,有些是浮動的,但一個numpy的陣列的D型必須是統一的;另一個是每行不是相同的長度,但numpy數組必須具有統一的(矩形)形狀。
我想你可能寧願做的是剛剛返回所有的三件事情:
comm_system
爲int數組,
score_list
爲float數組,
- 和
context_size
爲int (不是數組)。
你可以做到這一點與一個元組:
def new_agent(agent_type, context_size):
if agent_type == 'random':
comm_system = np.random.random_integers(0, 1, (meanings, signals))
if agent_type == 'blank':
comm_system = np.zeros((meanings, signals), int)
score_list = np.zeros(signals) #This is different too! No need to type out the 0, 0, ...
# now just return all three:
return comm_system, score_list, context_size
然後你就可以 「解壓」 的元組,像這樣:
random_agent, scores, size = new_agent('random', 5)
或者只是讓他們都在同一個元組:
random_agent_info = new_agent('random', 5)
而且你將有
In [331]: random_agent, scores, size = new_agent('random', 5)
In [332]: random_agent
Out[332]:
array([[0, 1, 1, 0],
[0, 1, 0, 1]])
In [333]: scores
Out[333]: array([ 0., 0., 0., 0.])
In [334]: size
Out[334]: 5
In [336]: random_agent_info
Out[336]:
(array([[1, 1, 0, 1],
[0, 1, 0, 0]]),
array([ 0., 0., 0., 0.]),
5)
In [337]: random_agent_info[0]
Out[337]:
array([[1, 1, 0, 1],
[0, 1, 0, 0]])
In [338]: random_agent_info[1]
Out[338]: array([ 0., 0., 0., 0.])
In [339]: random_agent_info[2]
Out[339]: 5
如果你想有comm_system
和score_list
是一個(3,2)
數組,你可以做到這一點:
def new_agent(agent_type, context_size):
...
return np.vstack([comm_system, score_list]), context_size
然後你會得到一個陣列和一個INT:
In [341]: random_agent, size = new_agent('random', 5)
In [342]: random_agent
Out[342]:
array([[ 1., 0., 1., 1.],
[ 1., 0., 1., 0.],
[ 0., 0., 0., 0.]])
In [343]: size
Out[343]: 5