@John 关于如何使用来自numpy.append 的 return 值是正确的,因为它不会修改原始数组。但是,您的预期输出存在问题:
[[0 1 0 0]
[1 1 0 1]
[0. 0. 0. 0.]
5]
不是一个可能的 numpy 数组,原因有二:一是有些元素是整数,有些是浮点数,但是 numpy 数组的 dtype 必须是统一的;另一个是每一行的长度不一样,但是numpy数组必须有统一的(矩形)形状。
我认为您可能更愿意做的是只返回所有三件事:
-
comm_system 作为整数数组,
-
score_list 作为浮点数组,
- 和
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