【问题标题】:Breaking out of user inputs in a list打破列表中的用户输入
【发布时间】:2015-11-04 05:26:39
【问题描述】:

我无法使用用户输入从展开的列表中分离出来。我想我错过了如何使用if 语句来查询特定项目的列表。当用户输入 -999 时,我需要列出请求输入的列表。我还需要从列表中排除 -999。你能帮帮我吗?

print(scoreLst) 可以在我使用它时进行测试,看看它是如何工作的。

scoreLst =[]
score = ()
lst1 = True

print("The list ends when user inputs -999")
scoreLst.append(input("Enter the test score: "))
while lst1 == True:
    score1 = scoreLst.append(input("Enter another test score: "))
    print(scoreLst)     
    if score1 != -999:
        lst1 ==  True
    else:
        scoreLst.remove(-999)
        lst1 == False

【问题讨论】:

  • 在验证后而不是之前添加到列表中

标签: python python-3.x


【解决方案1】:

几点说明:

  • 将测试成绩转换为int

  • list.append 返回None,不要将其分配给任何东西;使用scoreLst[-1] 而不是score1

  • 不要使用list.remove删除列表的最后一个元素,list.pop()会很好用

  • lst1 == False 是比较,lst1 = False 是赋值

  • 你会创建一个无限循环和break,一旦用户输入-999,我认为不需要lst1

最终结果:

scoreLst = []

print("The list ends when user inputs -999")
scoreLst.append(int(input("Enter the test score: ")))

while True:
    scoreLst.append(int(input("Enter another test score: ")))
    if scoreLst[-1] == -999:
        scoreLst.pop()
        break

【讨论】:

  • 这很好用而且更简单。出于好奇,我必须在下面分配 list.pop life 吗? scoreLst.pop(-999) 中断
  • @AndrewBodin list.pop() 删除列表的最后一个元素,最后一个元素是 -999(我们在scoreLst[-1] == -999 中专门检查了这一点),所以不,你不必做任何其他事情.
  • 顺便说一句,如果你觉得我的回答对你有帮助,你可以accept my answer
  • 我也很欣赏对事情为何如此运作的解释。它已被接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 2017-08-09
  • 2016-10-20
  • 1970-01-01
相关资源
最近更新 更多