繁体   English   中英

根据先前的条件更改列表中的值

[英]Change Value in a list based on previous condition

我有一个零和一的列表。 如果前一个值也是 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]

我尝试使用 for 循环无济于事。 有什么建议么?

这个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])

这里的想法是我们遍历列表,同时检查前一个元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM