【问题标题】:Searching a list and displaying whether or not the list contains the search variable搜索列表并显示列表是否包含搜索变量
【发布时间】:2015-07-20 00:05:00
【问题描述】:

我有一个 Twitter 管理器程序,其中一个选项是搜索包含用户提供的任何输入的推文。当在列表中找到匹配项时,我无法找到让 for 循环跳过 else 语句的方法。由于它现在工作,程序将打印它找到的与搜索条件匹配的推文,但也会打印没有找到包含搜索条件的推文。

# Option 3, search tweet_list for specific content and display if found
# in descending order starting with the most recent.
elif count == 3:
    tweet_list.reverse()
    if len(tweet_list) == 0:
        print('There are no tweets to search.', '\n')
    else:
        search = input('What would you like to search for? ')
        print('\nSearch Results')
        print('--------------')

        for n in tweet_list:
            a = n.get_author()
            b = n.get_text()
            c = n.get_age()

            if search in a or search in b:
                print(a + '-' + c + '\n' + b + '\n')                   

        else:
            print('No tweets contain "' + search + '".' + '\n')
            print('')

【问题讨论】:

    标签: for-loop for-else


    【解决方案1】:

    创建一个变量,比如found,并将其初始化为False。当你找到一条推文时,将其设置为True。然后将else: 替换为if not found:

    【讨论】:

    • 非常感谢!替换 else: 与 if not found: 如果未找到推文,则不显示消息,但我将其更改为 if found == "False" 并且所有似乎都与您的其他更改一起工作。
    • 当我提到TrueFalse 时,我指的是布尔值;看来您使用的是字符串,这就是您需要更改测试的原因。
    • 哦,我现在跟着你。我是新手,再次感谢您的帮助!
    猜你喜欢
    • 2020-11-17
    • 2019-04-27
    • 1970-01-01
    • 2014-03-09
    • 2015-04-09
    • 1970-01-01
    • 2020-06-26
    • 2013-10-28
    相关资源
    最近更新 更多