gpt4 book ai didi

python - 在 numpy 数组中的所有项目周围添加 0

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:15 24 4
gpt4 key购买 nike

我有一个 numpy 数组,我需要在不使用 for 循环(为了提高效率)的情况下在元素之间插入 0。

例如,[1, 1, 2, 2] 必须返回 [0, 1, 0, 1, 0, 2, 0, 2, 0]。我想到了numpy.where函数,但是我没有条件在里面使用。

最佳答案

无论哪种方式,您都必须创建一个新数组。一种方法是填充所需大小的缓冲区:

result = np.zeros(2 * a.size + 1, dtype=a.dtype)
result[1::2] = a

关于python - 在 numpy 数组中的所有项目周围添加 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59214541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com