搜索列表并显示列表是否包含搜索变量
问题描述:
我有一个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('')
答
创建一个变量,说found
,并初始化为False
。当您发现推文时,将其设置为True
。然后将else:
替换为if not found:
。
非常感谢!替换其他:如果未找到:如果未找到鸣叫,则不会显示消息,但如果找到,我将其更改为==“False”,并且似乎都与您的其他更改一起工作。 – Ben
当我提到'True'和'False'时,我的意思是布尔值;看起来你使用了字符串,这就是为什么你需要改变测试。 –
哦,我现在跟着你。我是新手,所以再次感谢您的帮助! – Ben