通过数组索引Python

2024-04-26 14:49:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组bound_1shape(1,5)

bound_1 = [ 0, 5, 9, 12, 14]

数组bound_2shape(1, 5)

bound_2 = [ 5, 9, 12, 14, 19]

值数组shape(1, 5)

value = [ 1, 2, 3, 4, 5]

结果数组,用零初始化,shape(1, 19)

result_array= [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

现在我要做的就是将值写入相应的范围(在bound1和bound2之间)到结果数组中,该数组应该如下所示

result_array= [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5]

我想是这样的:

result_array[ 0 , bound_1 : bound_2 ] = value

但我收到了一个错误:

IndexError: Invalid Slice

我正在尝试不使用for循环来解决这个问题。你知道吗


Tags: forvalue错误slice数组resultarraybound
2条回答

找到解决办法了!你知道吗

numpy.repeat ( value, bound_2-bound_1 )

here is the documentation of that function

我想不出一个可爱的“Python”的方式来回答这个问题。也许其他人会同意一个简短的表述。你知道吗

但是,以下内容应该可以完成这项工作:

for idx in range(0, len(bound_1)):
  for dst in range(bound_1[idx], bound_2[idx]):
    result_array[dst] = value[idx]

相关问题 更多 >