如何将数组复制到特定长度的数组

How to replicate array to specific length array

我想将一个小数组复制到特定长度的数组

示例:

var = [22,33,44,55] # ==> len(var) = 4
n = 13

我想要的新数组是:

var_new = [22,33,44,55,22,33,44,55,22,33,44,55,22]

这是我的代码:

import numpy as np
var = [22,33,44,55]
di = np.arange(13)
var_new = np.empty(13)
var_new[di] = var

我收到错误消息:

DeprecationWarning: assignment will raise an error in the future, most likely because your index result shape does not match the value array shape. You can use arr.flat[index] = values to keep the old behaviour.

但是我得到了我对应的变量:

var_new
array([ 22.,  33.,  44.,  55.,  22.,  33.,  44.,  55.,  22.,  33.,  44.,
    55.,  22.])

那么,如何解决这个错误呢?有其他选择吗?

首先,您没有收到错误,而是收到警告,如果 var_new[di] 的维度与 var 不匹配,则 var_new[di] = var 已弃用。

其次,错误信息告诉你怎么做:使用

var_new[di].flat = var

而且您不会再收到警告,并且保证可以正常工作。


如果不需要 numpy,另一种简单的方法是使用 itertools:

>>> import itertools as it
>>> var = [22, 33, 44, 55]
>>> list(<a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow noreferrer">it.islice</a>(<a href="https://docs.python.org/3/library/itertools.html#itertools.cycle" rel="nofollow noreferrer">it.cycle</a>(var), 13))
[22, 33, 44, 55, 22, 33, 44, 55, 22, 33, 44, 55, 22]

有更好的方法来复制数组,例如您可以简单地使用 np.resize:

Return a new array with the specified shape.

If the new array is larger than the original array, then the new array is filled with repeated copies of a. [...]

>>> import numpy as np
>>> var = [22,33,44,55]
>>> n = 13
>>> np.resize(var, n)
array([22, 33, 44, 55, 22, 33, 44, 55, 22, 33, 44, 55, 22])

用 [:] 复制数组(在 python 中称为列表),因为它们是可变的。 python 快捷方式只是乘以副本并再添加一个 元素。

>>> var = [22, 33, 44, 55]
>>> n = 3
>>> newlist = var[:]*n + var[:1]

给出你想要的13个元素

var = [22,33,44,55]
n = 13

可以在没有 numpy 的情况下使用 itertoolscycle()islice() 函数

来重复列表(或任何其他可迭代对象)
from itertools import cycle, islice
var_new = list(islice(cycle(var),0,n)