【问题标题】:Is it possible to make my else statement appear after the code is done checking every option?在代码检查完每个选项后,是否可以让我的 else 语句出现?
【发布时间】:2018-12-21 04:07:52
【问题描述】:

我有一个遍历二维列表的 while 循环,以查看它是否可以找到类似的提交以将其删除。

    i=0

while i <= len(my_list):
    if my_list[i] == userinput:
        del my_list[i]
        print("Entry Removed!")
    else:
        print("This publication does not exist")
    i+=1

如果没有找到匹配项,我想要代码打印消息“此出版物不存在”。但是,现在发生的情况是,每次比较一个项目时,代码都会打印该句子。

我明白为什么会发生这种情况,但我不知道如何解决它。解决此问题的最佳方法是什么?

编辑:将列表名称从“list”更改为“my_list”。我的不好,我在代码中实际上并没有这么称呼它,我只是在上传问题时更改了名称,以便于理解。

【问题讨论】:

  • 您在迭代列表时从列表中删除。这被认为是不好的做法。
  • ...基本上是因为它会跳过项目并导致索引错误。
  • 当您删除一个列表元素时,其余元素会向下移动一个。例如。如果您删除 x[2],那么 x[3] 将成为新的 x[2],x[4] 将成为 x[3],等等。更容易一次创建一个新列表,忽略那些您不需要。对了,不要用list作为变量名,它会屏蔽系统类list
  • 我知道你已经接受了这个答案,但是用户输入的例子是什么?是列表吗?
  • @Zev yes,userinput 是一个列表。

标签: python python-3.x loops if-statement while-loop


【解决方案1】:

你需要一个布尔值:

i = 0
found = False
while i <= len(list):
    if list[i] == userinput:
        del list[i]
        print("Entry Removed!")
        found = True
    i += 1

if not found:
    print("This publication does not exist")

一些不相关的建议:

  • 变量最好不要使用名称list
  • 在迭代同一个列表时不要从列表中删除项目。您可以反向迭代列表:

    i = len(li) - 1
    found = False
    while i >= 0:
        if li[i] == userinput:
            del li[i]
            print("Entry Removed!")
            found = True
        i -= 1
    
    if not found:
        print("This publication does not exist")
    

【讨论】:

  • 一个更好的方法是使用while循环评估器而不是使用列表的len。
  • @Sheshnath 我不确定你的意思
【解决方案2】:

Python 的 while 循环有一个 else 子句,如果循环完成而不中断它,则执行该子句:

但是让我们换一种方式来避免改变我们正在循环的列表:

list_ = [
    ["a", "b", "c"], 
    ["d", "f", "g"], 
    ["d", "f", "g"], 
    ["h", "i", "j"]
]

userinput = ["z", "z", "z"]
new_list = [x for x in list_ if x != userinput]

if list_ == new_list:
     print("This publication does not exist")

# This publication does not exist

不要覆盖list 关键字。我将其更改为 list_,但您可以将其更改为对您的应用程序更有意义的内容。

【讨论】:

  • 这不包括二维列表。
  • @VoNWooDSoN 这在 2d 列表上实际上是一样的(我对其进行了编辑以表明这一点,因为这更接近问题的要求)。我唯一关心的是时间/空间复杂性。此外,它对userinput 做了一个假设,但接受的答案似乎与userinput 是一个列表的假设相同。
  • 哦,我现在明白了...我假设用户输入是单个字符,而不是整行。但是您的解决方案确实与 OP 的匹配。
猜你喜欢
  • 1970-01-01
  • 2019-02-09
  • 1970-01-01
  • 1970-01-01
  • 2019-01-10
  • 1970-01-01
  • 2013-11-26
  • 2023-03-15
  • 2019-08-12
相关资源
最近更新 更多