我的 Python 程序必须在列表末尾添加或删除一个项目。添加的项目必须比列表中的最后一项大 1
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)
在“-”条件下放一个decrementor/decrease数字-
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
虽然其他答案解释了 i
的问题,但我想提出一种根本不需要此变量的方法。问题指出“添加的项目必须比列表中的最后一项大”。所以我们得到最后一项的值,将它增加一个并将这个增加的值附加到列表中。如果列表为空,我们使用默认值 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()
我的代码无法正常工作。在我输入 + + + - + 之后,它打印出 [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)
在“-”条件下放一个decrementor/decrease数字-
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
虽然其他答案解释了 i
的问题,但我想提出一种根本不需要此变量的方法。问题指出“添加的项目必须比列表中的最后一项大”。所以我们得到最后一项的值,将它增加一个并将这个增加的值附加到列表中。如果列表为空,我们使用默认值 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()