如何在列表中的字典字符串中搜索单词?

时间:2018-07-29 01:57:07

标签: python list dictionary search

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")

这是我当前的代码,但是当我为列表中的每个元素运行它时,它将打印“未找到结果”,如果存在,它将打印该结果。我希望它打印出那里的结果,或者只是没有找到结果。

2 个答案:

答案 0 :(得分:1)

仅使用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")

答案 1 :(得分:1)

仔细查看您的for循环正在做什么。

for i in range(len(dlGuestBook)): # for each entry in the guestbook
        if CommentSearch in dlGuestBook[i]["Comment"]:
            # print the comment
        else:
            print("No results found")

我认为您想要的是在循环结束后仅打印“未找到结果”(如果未找到任何结果)。这样的事情可能是解决方案。

foundComment = False
for i in range(len(dlGuestBook)):
    if CommentSearch in dlGuestBook[i]["Comment"]:
        foundComment = True
        # print the comment

if not foundComment:
    print("No results found")
相关问题