【问题标题】:Is there a way to insert elements from a list to every knth position in second list?有没有办法将列表中的元素插入到第二个列表中的每个第 kn 个位置?
【发布时间】:2020-08-04 02:05:41
【问题描述】:

我需要将我的第一个列表中的所有元素放置到第二个列表的第 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]

位置是二维的。我正在尝试使用 numpy 找到最有效的(时间和空间)方法。

注意:上面的代码确实有效。我只是想让它更有效率。

【问题讨论】:

标签: python numpy


【解决方案1】:

只需使用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]

编写此代码时没有损坏循环。

【讨论】:

  • 这正是我想要的!谢谢。
【解决方案2】:

如果你输入的其实是两个lists,这里就没有必要使用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 更快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多