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

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

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

最佳答案

仅使用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/

相关文章:

python - 带范围的字典理解

python - 我怎样才能解决这个脚本中的内存限制?

python - 从 python27 中的文件夹导入模块

string - Racket 中列表到字符串的转换

python - 过滤字典列表以始终返回单个字典,给定要查找的默认键值

c# - 当键包含在第二个字典中时,从字典中选择所有元素

python - 如何使用python从git存储库下载单个文件

python - Perforce API : Get Latest Revision of a Subdirectory

c - 链接列表,在函数中将列表头作为参数传递时不起作用

c# - 字典包含键并在一个函数中获取值