简体   繁体   中英

Python replace elements in array at certain range

I've an array, for example:

Array = [100]*100

Then I want to do this:

Array[0:10] = 1

The Array should look like this:

Array = [1,1,1,1,1,1,1,1,1,1,100,100....,100]

But Python says No and gives me

Array[0:10] = 1 can only assign an iterable

What does it want and how can I fix it?

您可以使用array[0:10] = [1] * 10 ,您只需要制作一个要替换的切片大小的数组即可。

Another way is to turn your list into a numpy array, and numpy will broadcast your value to the whole part of the array:

import numpy as np

a = np.array([100]*100)

a[0:10] = 1
print(a)

# array([  1,   1,   1,   1,   1,   1,   1,   1,   1,   1, 100, 100, 100,
#        100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
#        ... 
#       ])

I'll give you an example with list:

L = [0 for k in range(100)] # List of 0
L[10:20] = [1 for k in range(10)]

# Output:
L = [0, ..., 0, 1, 1, ..., 1, 0, ..., 0]

You need to give a list as well to replace N values.

在这种情况下,双方的操作数类型应相同

Array[0:10]=[1]*10

lists in python are mutable it's not good to write them in the form [100]*100. You might have problems later when your code gets complicated.

I suggest to write it as:

array = [100 for _ in range(100)]
for i in range(10):
    array[i] = 1
print(array)

output: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM