简体   繁体   English

搜索列表并显示列表是否包含搜索变量

[英]Searching a list and displaying whether or not the list contains the search variable

I have a Twitter manager program where one option is searching for tweets containing whatever input the user provides. 我有一个Twitter管理器程序,其中一个选项是搜索包含用户提供的任何输入的推文。 I am unable to figure out a way to have the for loop skip the else statement when there is a match found in the list. 当列表中找到匹配项时,我无法找出让for循环跳过else语句的方法。 As it works now, the program will print the tweet it finds that matches the search criteria, but also prints that no tweet is found containing the search criteria. 现在开始运行,程序将打印找到的符合搜索条件的推文,但还会打印未找到包含搜索条件的推文。

# 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('')

Create a variable, say found , and initialize it to False . 创建一个说found的变量,并将其初始化为False When you find a tweet, set it to True . 找到推文后,将其设置为True Then replace the else: with if not found: . 然后将else:替换为if not found:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM