簡體   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