在numpy中为多个切片赋值

goz*_*lli 11 python arrays matlab numpy slice

在Matlab中,您可以为同一列表的多个切片分配值:

>> a = 1:10

a =

     1     2     3     4     5     6     7     8     9    10

>> a([1:3,7:9]) = 10

a =

    10    10    10     4     5     6    10    10    10    10
Run Code Online (Sandbox Code Playgroud)

如何在Python中使用numpy数组执行此操作?

>>> a = np.arange(10)

>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> a[1:3,7:9] = 10
IndexError: too many indices
Run Code Online (Sandbox Code Playgroud)

Jos*_*del 13

您也可以考虑使用np.r_:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html

ii = np.r_[0:3,7:10]
a[ii] = 10

In [11]: a
Out[11]: array([ 10, 10, 10,  3,  4,  5,  6, 10, 10,  10])
Run Code Online (Sandbox Code Playgroud)


Jor*_*ley 8

a = np.arange(10)
a[[range(3)+range(6,9)]] = 10
#or a[[0,1,2,6,7,8]] = 10 

print a
Run Code Online (Sandbox Code Playgroud)

这应该工作我想...我不知道它是你想要的