通过重复固定范围的值来扩展列表

问题描述 投票:0回答:1

我有3个不同范围的列表,并希望通过重复具有较低范围的列表的数字序列来对齐范围。最后,所有列表应该具有范围50.列表2当前具有30的范围。因此,前20个元素必须重复达到50.列表3当前具有15的范围。因此,列表将是完全重复两次,第五次重复将在5个元素后停止(50-15 = 35个要填充的元素)。

from scipy.interpolate import InterpolatedUnivariateSpline
import numpy as np

a1, a1_ = np.array([0, 14, 39, 49]), np.linspace(0, 49, 50)
Y1 = np.array([0, 2.5, 2.5, 1.25])
a2, a2_ = np.array([0, 7, 19, 29]), np.linspace(0, 29, 30)
Y2 = np.array([0, 8, 8, 5])
a3, a3_ = np.array([0, 4, 9, 14]), np.linspace(0, 14, 15)
Y3 = np.array([0, 10, 10, 8])

Y_int1 = InterpolatedUnivariateSpline(a1, Y1, k=1)
Y_int2 = InterpolatedUnivariateSpline(a2, Y2, k=1)
Y_int3 = InterpolatedUnivariateSpline(a3, Y3, k=1)

Y_ = [Y_int1(a1_), Y_int2(a2_), Y_int3(a3_)]

# A working, but not elegant, solution for the second list is:
Y_[1] = np.append(Y_[1], [Y_[1][0:len(Y_[0]) - len(Y_[1])]])

# However for Y_[2] this does not work as the entire list has to be repeated (2.33 times). 
python list append
1个回答
1
投票

你可以这样做:

import numpy as np

L = 50
arrs = [np.linspace(0, 49, 50), np.linspace(0, 29, 30), np.linspace(0, 14, 15)]
arrs = [np.r_[np.tile(a, L // len(a)), a[:L % len(a)]] for a in arrs]

arrs的内容:

[array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,
         11.,  12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,
         22.,  23.,  24.,  25.,  26.,  27.,  28.,  29.,  30.,  31.,  32.,
         33.,  34.,  35.,  36.,  37.,  38.,  39.,  40.,  41.,  42.,  43.,
         44.,  45.,  46.,  47.,  48.,  49.]),
 array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,
         11.,  12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,
         22.,  23.,  24.,  25.,  26.,  27.,  28.,  29.,   0.,   1.,   2.,
          3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,  12.,  13.,
         14.,  15.,  16.,  17.,  18.,  19.]),
 array([  0.,   1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,
         11.,  12.,  13.,  14.,   0.,   1.,   2.,   3.,   4.,   5.,   6.,
          7.,   8.,   9.,  10.,  11.,  12.,  13.,  14.,   0.,   1.,   2.,
          3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,  12.,  13.,
         14.,   0.,   1.,   2.,   3.,   4.])]

分解

  • np.tile字面上“tile”一个数组,也就是说,它连接同一个数组的几个副本。这里np.tile(a, L // len(a))瓦片的次数是所需长度L和数组长度len(a)的整数除法;对于50,它将是1,对于15,它将是2,对于60,它将是0。
  • a[:L % len(a)]从数组的开头到L以其模数的长度取一个切片。这是您需要填充L元素的数组的最终“部分副本”。对于50,它将是0,对于15将是5,对于60将是50.在所有情况下,请注意显然len(a) * (L // len(a)) + (L % len(a)) = L,意味着连接这两个部分的结果将始终具有大小L
  • np._r只是一个缩写语法,在这种情况下,沿着第一维连接。在这里,它相当于np.concatenate([np.tile(a, L // len(a)), a[:L % len(a)]])
© www.soinside.com 2019 - 2024. All rights reserved.