Replacing List Items
There is a list of integers. Replace negative by -1, positive - by number 1, keep zero unchanged.
1st option - filling a new list depending on the values of the first one:
listOrigin = [10, -15, 3, 8, 0, 9, -6, 13, -1, 5] listMask = [] for item in listOrigin: if item > 0: listMask.append(1) elif item < 0: listMask.append(-1) else: listMask.append(0) print(listOrigin) print(listMask)
With comments:
# the old list listOrigin = [10, -15, 3, 8, 0, 9, -6, 13, -1, 5] # the new list listMask = [] # enumeration of the elements of the old list for item in listOrigin: if item > 0: # If the element is greater than 0, listMask.append(1) # 1 is added to the new list. elif item < 0: # If the element is less than 0, listMask.append(-1) # -1 is added to the list. else: # If the element is 0, listMask.append(0) # 0 is added to the list. # output of source and derived lists print(listOrigin) print(listMask)
2nd option - replacing items directly in the source list:
listOne = [10, -15, 3, 8, 0, 9, -6, 13, -1, 5] print(listOne) for i in range(len(listOne)): if listOne[i] > 0: listOne[i] = 1 elif listOne[i] < 0: listOne[i] = -1 print(listOne)
With comments:
listOne = [10, -15, 3, 8, 0, 9, -6, 13, -1, 5] print(listOne) # the list in its original form # The i value changes from 0 to # the index of the last item in the list, # which is equal to the length of the list minus 1. for i in range(len(listOne)): if listOne[i] > 0: # If an element with index i is greater than 0, listOne[i] = 1 # then it is replaced by 1. elif listOne[i] < 0: # If an element with index i is less than 0, listOne[i] = -1 # then it is replaced by -1. # In all other cases (the item is 0) # the element will remain as it is. print(listOne) # output of the changed list
The result of an execution of scripts:
[10, -15, 3, 8, 0, 9, -6, 13, -1, 5] [1, -1, 1, 1, 0, 1, -1, 1, -1, 1]