我需要将所有元素从第一个列表放置到第二个列表的第k个位置。其中k = 0,1,2...
和n是单个数字。目前,我正在执行此操作(使用numpy)
#create numpy array
positionList = np.array([])
positions = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
epochs = np.array([10, 11, 12])
for pos,epoch in zip(positions,epochs):
position = np.insert(pos,0,epoch)
if len(positionList) > 0:
positionList = np.concatenate((positionList,position))
else:
positionList = position
positionList = np.around(positionList,1).tolist()
#expected output [10, 1, 2, 3, 11, 4, 5, 6, 12, 7, 8, 9]
位置为2D。我正在尝试找到最有效的方式(时间和空间)来使用numpy进行此操作。
注意:以上代码确实有效。我只是想提高效率。
答案 0 :(得分:2)
只需使用np.concatenate()
的axis
参数:
import numpy as np
positions = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
epochs = np.array([10, 11, 12])
print(np.concatenate([epochs[..., None], positions], axis=1).ravel())
# [10 1 2 3 11 4 5 6 12 7 8 9]
编写此代码时不会损坏循环。
答案 1 :(得分:1)
如果您输入的实际上是两个list
,则无需在此处使用NumPy:
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [10, 11, 12]
print([z for x, y in zip(b, a) for z in [x] + y])
# [10, 1, 2, 3, 11, 4, 5, 6, 12, 7, 8, 9]
%timeit [z for x, y in zip(b, a) for z in [x] + y]
# 1000000 loops, best of 3: 1.04 µs per loop
或者,如果a
是平坦的,并且您每个n
元素都指定了中断:
n = 3
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [10, 11, 12]
print([z for x, y in zip(b, zip(*[iter(a)] * n)) for z in (x,) + y])
# [10, 1, 2, 3, 11, 4, 5, 6, 12, 7, 8, 9]
%timeit [z for x, y in zip(b, zip(*[iter(a)] * n)) for z in (x,) + y]
# 1000000 loops, best of 3: 1.31 µs per loop
为了进行比较,这是基于NumPy的解决方案:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([10, 11, 12])
print(np.concatenate([b[..., None], a], axis=1).ravel().tolist())
# [10, 1, 2, 3, 11, 4, 5, 6, 12, 7, 8, 9]
%timeit np.concatenate([b[..., None], a], axis=1).ravel().tolist()
# 100000 loops, best of 3: 2.43 µs per loop
这些表明,至少对于您的输入而言,基于Python list
的解决方案实际上比诉诸NumPy更快。