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:
list_origin = [10, -15, 3, 8, 0, 9, -6, 13, -1, 5]
list_mask = []
for item in list_origin:
if item > 0:
list_mask.append(1)
elif item < 0:
list_mask.append(-1)
else:
list_mask.append(0)
print(list_origin)
print(list_mask)
With comments:
# the old list
list_origin = [10, -15, 3, 8, 0, 9, -6, 13, -1, 5]
# the new list
list_mask = []
# enumeration of the elements of the old list
for item in list_origin:
if item > 0: # If the element is greater than 0,
list_mask.append(1) # 1 is added to the new list.
elif item < 0: # If the element is less than 0,
list_mask.append(-1) # -1 is added to the list.
else: # If the element is 0,
list_mask.append(0) # 0 is added to the list.
# output of source and derived lists
print(list_origin)
print(list_mask)
2nd option - replacing items directly in the source list:
a = [10, -15, 3, 8, 0, 9, -6, 13, -1, 5]
print(a)
for i in range(len(a)):
if a[i] > 0:
a[i] = 1
elif a[i] < 0:
a[i] = -1
print(a)
With comments:
a = [10, -15, 3, 8, 0, 9, -6, 13, -1, 5]
print(a) # 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(a)):
if a[i] > 0: # If an element with index i is greater than 0,
a[i] = 1 # then it is replaced by 1.
elif a[i] < 0: # If an element with index i is less than 0,
a[i] = -1 # then it is replaced by -1.
# In all other cases (the item is 0)
# the element will remain as it is.
print(a) # 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]