How to Replace Negative Integers in a Python Array
- 1). Open a Python program file and type the following code:
from array import *
This line imports the array class into the program so you can create and edit arrays. - 2). Type the following code:
def replaceArray( ar ):
-->newArray = array('i',[])
-->for i in ar:
--> -->if i < 0:
--> --> -->newArray.append(0)
--> -->else:
--> --> -->newArray.append(i)
-->return newArray
Remember to indent properly. Each "-->" represents one indent, whether you use spaces or tabs to do so. The first line creates a function called "replaceArray" that takes an array as a parameter. The second line creates a new array to copy values from the old one. The third line starts a loop to cycle through each element in the array. While doing this, the fourth through seventh lines check to see if the current element is a negative integer. If so, it replaces it with zero and appends it to the new array. If not, it just appends that value to the new array. You can replace the negative integers with something else you need. The last line returns the new array with the replaced values. - 3). Save the Python program file and run it in your Python shell environment.
- 4). Type the following code:
myArr = array('i', [1, -2, 3, -4, 5])
myArr = replaceArray(myArr)
The first line creates an array with both positive and negative integers in it. You may already have an array created elsewhere in your program. The second line overwrites that array by passing it to the function you created that swaps out negative integers with zeros. The new values "[1, 0, 3, 0, 5]" are now in the "myArr" array.
Source...