For loop 搜索列表并显示列表是否包含搜索变量
我有一个Twitter管理程序,其中一个选项是搜索包含用户提供的任何输入的tweet。当列表中找到匹配项时,我无法找到让for循环跳过else语句的方法。当它现在工作时,程序将打印它找到的与搜索条件匹配的tweet,但也打印没有找到包含搜索条件的tweetFor loop 搜索列表并显示列表是否包含搜索变量,for-loop,for-else,For Loop,For Else,我有一个Twitter管理程序,其中一个选项是搜索包含用户提供的任何输入的tweet。当列表中找到匹配项时,我无法找到让for循环跳过else语句的方法。当它现在工作时,程序将打印它找到的与搜索条件匹配的tweet,但也打印没有找到包含搜索条件的tweet # Option 3, search tweet_list for specific content and display if found # in descending order starting with the most rece
# 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('')
创建一个变量,例如
found
,并将其初始化为False
。找到tweet后,将其设置为True
。然后将else:
替换为如果找不到:
非常感谢!替换else:if not found:if not found not found not display the message if tweet not found,但我将其更改为if found==“False”,所有更改似乎都与您的其他更改一起工作。当我提到True
和False
时,我指的是布尔值;看起来您使用了字符串,这就是为什么您需要更改测试的原因。哦,我现在就听您的。我是新手,再次感谢你的帮助!