2

I have array with values sourceArray and I have array with values to replace toReplace. I want to replace all values that are in sourceArray that are equal to values in toReplace array.

Is there some smart way to do it in Python ?

E.g.

 sourceArray = [0,1,2,3,4,5,5,6,7]
 toReplace = [5,6]

After replace I want to have

 sourceArray = [0,1,2,3,4,0,0,0,7]
Darqer
  • 2,847
  • 9
  • 45
  • 65
  • Why not just iterate on your first array (sourceArray) and when the index of i == toReplaceArray[j], then you transform it to 0? In this, you'd need one loop and one inner loop * – Kevin Avignon Mar 16 '18 at 22:07
  • I feel that there is a smarter way to do it in Python :) – Darqer Mar 16 '18 at 22:08

2 Answers2

5

List comprehension with conditional expression:

[0 if i in toReplace else i for i in sourceArray]

If the toReplace list is too big, it's preferable to make it a set to get O(1) lookup.

Example:

In [21]:  sourceArray = [0,1,2,3,4,5,5,6,7]
    ...:  toReplace = [5,6]
    ...: 

In [22]: [0 if i in toReplace else i for i in sourceArray]
Out[22]: [0, 1, 2, 3, 4, 0, 0, 0, 7]
heemayl
  • 39,294
  • 7
  • 70
  • 76
1

you Can use list comprehensions:

 new_list = [x if toReplace.count(x)==0 else 0 for x in sourceArray]
py-D
  • 661
  • 5
  • 8