在给定特定索引处的起始值的位置填写列表

时间:2017-11-22 17:45:05

标签: python list numpy

我有一个起始值列表,这些起始值都应该进入新列表的索引152,该列表从起始值(在第152个索引处)到某个最大值,然后再从零开始再到一些起始值规则间距。

为了使一个更简单的例子更清楚,想象我的起始列表如下所示:[3,4,1,2]并将这些起始值分配给长度为8的新列表的第二个索引间隔从最小值1到最大值4.我需要生成四个列表,如下所示:

[2.5, 3 ,3.5,4,0.5,1,1.5,2],其中3为第二个指数的起始值

[3.5, 4 ,0.5,1,1.5,2,2.5,3],其中4为第二个指数的起始值

[0.5, 1 ,1.5,2,2.5,3,3.5,4],其中1为第二个指数的起始值

[1.5, 2 ,2.5,3,3.5,4,0.5,1],其中2为第二个指数的起始值

我的实际起始列表是20个条目长,所以我需要生成20个新列表,其中每个起始值都在192索引长列表的第152个索引中。最小值为0,最大值为24.因此从起始值开始,列表的其余部分应以偶数增量填充,从起始值到最大值,然后从最小值返回到起始值 - 增量保持第152个索引的起始值。

我希望这是有道理的。很难解释,也可能是我编写代码时遇到问题的原因。我知道如何做到这一点,但是我很好奇是否有一种明显的pythonic方式我还没有学到。谢谢!

编辑:

这就是我所拥有的:

nlon = 192
lon_idx = 152
lt = [19.6, 19.65, 19.7]

spacing = 24/nlon
nbefore = lon_idx - 1
nafter = nlon - lon_idx
time_dict = {}
for i in lt:
    b = nbefore
    a = nafter
    temp = [i]
    while b > 0:
        val = temp[0]-spacing
        if val < 0:
            temp.insert(0, 24)
        else:
            temp.insert(0, val)
        b -= 1
    while a > 0:
        val = temp[-1]+spacing
        if val > 24:
            temp.append(0)
        else:
            temp.append(val)
        a -= 1
    time_dict['lst_%s' % i] = temp

print (time_dict['lst_19.65'][151])

它有效,但它不漂亮。我还需要按顺序保留这些新列表,因为它们与另一个numpy数组中的数据有关。

1 个答案:

答案 0 :(得分:1)

这里有一些代码可以将新数组构建为2D Numpy数组中的行。它使用您已经显示的简化数据,但如果我已正确理解您的描述,它也应该适用于您的大型数据集。 ;)

关键的想法是使用条目之间的所需步骤构建数组base。然后我们轮换base,这样当我们将它与起始值组合时,它们将出现在正确的列中。我们使用模运算来确保新数组的所有值都在所需的范围内。

import numpy as np

# The starting values in a column array
lt = np.array([3, 4, 1, 2])[:, None]

# The number of entries in the new arrays
num_entries = 8

# The offset in the new arrays of the starting values
offset = 1

# The highest value permitted in the new arrays
hi = 4

# Step size between the values in the new arrays
delta = hi / num_entries

# Create an array of the steps
base = np.linspace(0, hi, num=num_entries, endpoint=False)
# And rotate it so the starting values are at the correct offset
base = np.roll(base, offset)

# Build the new arrays
new_arrays = (base + lt - delta) % hi + delta
print(new_arrays)

<强>输出

[[ 2.5  3.   3.5  4.   0.5  1.   1.5  2. ]
 [ 3.5  4.   0.5  1.   1.5  2.   2.5  3. ]
 [ 0.5  1.   1.5  2.   2.5  3.   3.5  4. ]
 [ 1.5  2.   2.5  3.   3.5  4.   0.5  1. ]]
相关问题