有效地将一个元素附加到大型 numpy 数组中的每个列表 [英] Efficiently append an element to each of the lists in a large numpy array
问题描述
我有一个非常大的 numpy 列表数组,我想向每个数组附加一个元素.为了性能,我想避免使用循环.
I have a really large numpy of array of lists, and I want to append an element to each of the arrays. I want to avoid using a loop for the sake of performance.
以下语法不起作用.
a=np.array([[],[1],[0,1]])
[j.append(3) for j in a]
这个例子的预期结果是
np.array([[3],[1,3],[0,1,3])
但是我得到了
[None, None, None]
有什么线索吗?
推荐答案
list.append()
返回 None
,所以你只是看到了 3 个追加操作每个都返回 None
.
list.append()
returns None
, so you're just seeing that the 3 append operations each returned None
.
但是,如果您打印 a
的内容,您会发现追加成功.
However, if you print the contents of a
you'll find that the appends were successful.
a=np.array([[],[1],[0,1]])
[j.append(3) for j in a]
print(a)
# prints "[list([3]) list([1, 3]) list([0, 1, 3])]"
我不建议为任何事情使用 numpy 列表数组,但也许您有一些特殊的用例,这是有意义的.我建议问一个单独的问题,看看使用 numpy 列表数组的原因
I wouldn't recommend using a numpy array of lists for anything, but maybe you have some special use case where this makes sense. I suggest asking a separate quesiton that looks at the reasoning for using a numpy array of lists
这篇关于有效地将一个元素附加到大型 numpy 数组中的每个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!