简体   繁体   中英

Python equivalent to replace() in R

Is there a powerful replace function in Python, something equivalent to replace(x, l, y) in R? eg

x = [0,0,0,0,0,0,0,0,0, 0]
l = [True,False,True,True,False,False,False,False,True, False]
y = [5, 6, 7, 8]

The number of values in y matches the number of True in l. In R, replace(x, l, y) will have x replaced by y corresponding to the True positions in l.

Is there a similar function in Python I can call? If not, any suggestions how to make it working?

Thanks much in advance!

Since the number of True s and the number of elements in y are the same, we can a generator over y , and then use a list comprehension to build the result. We extract from y if the corresponding element in l is True , else we extract from x :

iter_y = iter(y)

[next(iter_y) if l_item else x_item for l_item, x_item in zip(l, x)]

This outputs:

[5, 0, 6, 7, 0, 0, 0, 0, 8, 0]

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