是否可以为numpy数组切片的偶数和奇数元素分配不同的值?
将起作用的代码示例:
a=np.zeros(100)
b=np.arange(10,50,10)
print(a)
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0.]
a[b]=10
print(a)
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 10. 0. 0. 0. 0. 0. 0. 0.
0. 0. 10. 0. 0. 0. 0. 0. 0. 0. 0. 0. 10. 0. 0. 0. 0. 0.
0. 0. 0. 0. 10. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
现在,我正在尝试为切片a [b]的偶数和奇数元素分配不同的数字
a[b][::2] = 10
a[b][1::2] = -10
但这不起作用,初始的零数组不会修改。
简短通知-实际上,b和a是动态生成的,因此我通常不知道它们的形状(a和b)以及哪些索引在(b)以内
答案 0 :(得分:0)
您应直接为b
编制索引:
import numpy as np
a = np.zeros(100)
b = np.arange(10,50,10)
a[b[::2]] = 10
a[b[1::2]] = -10
print(a[b])
# [ 10. -10. 10. -10.]