[英]Is it possible to make my else statement appear after the code is done checking every option?
I have a while loop that goes over a two-dimensional list, to see if it can find a similar submission for it to be removed. 我有一个遍历二维列表的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
What I wanted was for the code to print the message "This publication does not exist" if no matches were found. 如果没有找到匹配项,我想要的是代码打印消息“此发布不存在”。 However, what happens right now is that everytime it compares an item, the code prints the sentence.
但是,现在发生的事情是,每当它比较一个项目时,代码就打印出句子。
I understand why this happens but I have no idea how to fix it. 我明白为什么会这样,但我不知道如何解决它。 What is the best way of addressing this issue?
解决这个问题的最佳方法是什么?
EDIT: Changed list name from "list" to "my_list". 编辑:将列表名称从“列表”更改为“my_list”。 My bad, I didn't actually call it that in the code, I just changed the name when uploading the question for ease of understanding.
我的不好,我实际上并没有这么称呼它在代码中,我只是在上传问题时更改了名称以便于理解。
You'll need to a boolean: 你需要一个布尔值:
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")
Some unrelated suggestions: 一些不相关的建议:
list
for a variable list
用于变量 Don't remove items from a list while iterating that same list. 迭代同一列表时,请勿从列表中删除项目。 You can iterate the list in reverse:
您可以反向迭代列表:
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")
Python's while loop has an else clause that executes if the loop completes without breaking out of it: Python的while循环有一个else子句,如果循环完成而不会中断它就会执行:
But let's go another way with this to avoid changing a list we are looping over: 但是,让我们采取另一种方式来避免更改我们正在循环的列表:
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
Don't overwrite the list
keyword. 不要覆盖
list
关键字。 I changed it to list_
but you can change it to something more meaningful for your application. 我将其更改为
list_
但您可以将其更改为对您的应用程序更有意义的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.