簡體   English   中英

我的 Python 程序必須在列表末尾添加或刪除一個項目。 添加的項目必須比列表中的最后一項大一

[英]My Python program has to add or remove an item in the end of a list. The item that is added must be one greater than the last item in the list

我的代碼不能正常工作。 在我輸入 + + + - + 之后,它會打印出 [1, 2, 4] 而不是 [1, 2, 3]。 我認為 i-value 存在一些問題,但我不知道如何解決它。 請幫助我您的建議!

list = []
i = 1

while True:
    print((f"Now {list}"))
    
    n = input("add or remove:")
           
    if n == "+":
        list.append(i)
        i+=1

    if n == "-":
        list.pop(-1)

在“-”條件下放置一個減量器/減少數字 -

if n == "-":
    list.pop() # This is equivalent to .pop(-1) - Removes last item

    if i != 0: # If list is empty then don't remove
        i -= 1 # This will reduce the number and give expected output

這是代碼:

列表 = [] 我 = 0

while True: print((f"Now {list}"))

n = input("add or remove:")
       
if n == "+":
    i+=1
    list.append(i)

if n == "-":
    i-=1
    list.pop()

雖然其他答案解釋了我的問題,但i想提出一種根本不需要這個變量的方法。 問題指出“添加的項目必須比列表中的最后一項大一”。 所以我們得到最后一項的值,將其增加一,並將 append 這個增加的值添加到列表中。 如果列表為空,我們使用默認值1

data = []
while True:
    print(f"Now {data}")
    n = input("add or remove:")
    if n == "+":
        new_value = data[-1] + 1 if data else 1
        data.append(new_value)
    elif n == "-":
        data.pop()

您是否嘗試用“elif”替換第二個“if”?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM