Change Value In A List Based On Previous Condition
I have a list of zeros and ones. I am trying to replace the a value of 1 with a 0 if the previous value is also a 1 for a desired output as shown below. list = [1,1,1,0,0,0,1,0
Solution 1:
How about this for loop:
list = [1,1,1,0,0,0,1,0,1,1,0]
new_list = []
ant=0
for i in list:
if ant ==0 and i==1:
new_list.append(1)
else:
new_list.append(0)
ant=i
Solution 2:
question_list = [1,1,1,0,0,0,1,0,1,1,0]
new_list = [question_list[0]] # notice we put the first element herefor i inrange(1, len(question_list) + 1):
# check if the current and previous element are 1if question_list[i] == 1and question_list[i - 1] == 1:
new_list.append(0)
else:
new_list.append(question_list[i])
The idea here is we iterate over the list, while checking the previous element.
Post a Comment for "Change Value In A List Based On Previous Condition"