[英]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.
如果前一个值也是 1 以获得所需的 output,我正在尝试将值 1 替换为 0,如下所示。
list = [1,1,1,0,0,0,1,0,1,1,0]
new_list = [1,0,0,0,0,0,1,0,1,0,0]
I've tried using a for loop to no avail.我尝试使用 for 循环无济于事。 Any suggestions?
有什么建议么?
How about this for loop:这个for循环怎么样:
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
question_list = [1,1,1,0,0,0,1,0,1,1,0]
new_list = [question_list[0]] # notice we put the first element here
for i in range(1, len(question_list) + 1):
# check if the current and previous element are 1
if question_list[i] == 1 and 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.这里的想法是我们遍历列表,同时检查前一个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.