def SearchEntryComment():
print("\n\nSearch for guestbook comment with a keyword\n")
CommentSearch = input("Enter key word for search: ")
for i in range(len(dlGuestBook)):
if CommentSearch in dlGuestBook[i]["Comment"]:
print(i+1, ".", dlGuestBook[i] ["FirstName"], dlGuestBook[i]["LastName"], dlGuestBook[i]["Date"])
print(dlGuestBook[i]["Comment"], "\n")
else:
print("No results found")
print("\n")
这是我当前的代码,但是当我对列表中的每个元素运行它时,它将打印“未找到结果”,如果存在,它将打印该结果。我希望它要么打印存在的结果,要么打印没有找到的结果。
最佳答案
仅使用resultCount
来保存列表中找到的结果的计数,并在for循环后检查计数。
def SearchEntryComment():
print("\n\nSearch for guestbook comment with a keyword\n")
CommentSearch = input("Enter key word for search: ")
resultCount = 0
for i in range(len(dlGuestBook)):
if CommentSearch in dlGuestBook[i]["Comment"]:
print(i+1, ".", dlGuestBook[i] ["FirstName"], dlGuestBook[i]["LastName"], dlGuestBook[i]["Date"])
print(dlGuestBook[i]["Comment"], "\n")
resultCount += 1
if resultCount == 0:
print("No results found")
print("\n")
关于python - 如何在列表中的字典字符串中搜索单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51576629/