【发布时间】:2021-06-11 14:09:03
【问题描述】:
我想要一个 numpy 数组,每个数组元素将是另一个整数数组(或 python 列表)。
import numpy as np
arr = np.empty(2, dtype=int) # what to put here? int? list?
arr = np.append(arr, [0,1]) # there will be always exactly two numbers added
arr = np.append(arr, [1,1])
arr = np.append(arr, [5,1])
# and so on - I want to append undefined amount of times, these numbers are computed at runtime
我得到了什么:
0: 0
1: 1
2: 1
3: 1
4: 5
5: 1
我想得到什么:
0: [0,1]
1: [1,1]
2: [5,1]
这里的重点是我想在之后迭代:
for element in arr:
x = element[0]
y = element[1]
# do something with x and y here
因为这已经实现了,我不想重构很长的代码。 您能否告诉我任何解决方案,如何正确初始化这个数组,以及哪些(元组、列表、numpy 数组)应该在那里存储整数,以使其尽可能快?
谢谢
【问题讨论】:
-
你看到文档中关于
axis的注释了吗?重复append很慢。不要这样做,特别是如果您不了解尺寸或文档。 -
列表列表将是最快的,无论是创建还是迭代访问。
-
@hpaulj 我会试一试,非常感谢您的宝贵时间!
标签: python arrays list performance numpy