[英]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.