Python3,如果在列表中找到一项;“打印它”;“其他打印”;“未找到”;

Python3,如果在列表中找到一项;“打印它”;“其他打印”;“未找到”;,python,python-3.x,list,beautifulsoup,Python,Python 3.x,List,Beautifulsoup,我正试图打印从网站回复列表中找到的单词,否则如果未找到,请打印“未找到”。但是我的脚本打印了它找到的单词。但它也会为列表中的每个项目打印“未找到”。如果列表中没有找到任何内容,我只需要打印“未找到” 我的剧本: response = requests.post(URL, headers=Headers, cookies=Cookies, data=Data) content = response.content status_type = [b'Approved', b'Pending', b

我正试图打印从网站回复列表中找到的单词,否则如果未找到,请打印“未找到”。但是我的脚本打印了它找到的单词。但它也会为列表中的每个项目打印“未找到”。如果列表中没有找到任何内容,我只需要打印“未找到”

我的剧本:

response = requests.post(URL, headers=Headers, cookies=Cookies, data=Data)

content = response.content
status_type = [b'Approved', b'Pending', b'Rejected', b'Issued']

for status in status_type:
    if status in content:
        print(status.decode())
    if status not in content:
        print("Not Found")
我的脚本的输出:

最明显的方法就是简单地使用一个标志来查看是否找到了:

found = False
for status in status_type:
    if status in content:
        print(status.decode())
        found = True
        # break if you only want the first one found
if not found:
    print("Not Found")
的标志方法可能是最直接的;另一种方法是将找到的状态收集到列表中,然后进行处理:

found_statuses = [status.decode() for status in status_type if status in content]

if found_statuses:
    print(', '.join(found_statuses))
else:
    print('Not Found')
如果您需要在发现多个状态时采取特殊措施,并且在这种情况下不需要打印它们(或以不同的方式打印它们),这将特别有用:


您还可以将结果存储在另一个列表中并打印

result = [status.decode() for status in status_type if status in content]
if len(result) == 0:
   print("Not Found")
else:
   for status in result:
       print(status)

对象将在列表中或不在列表中。因此,您的第二个语句应该使用
elif
而不是
if
@Noah,实际上,没有条件的
else
也可以执行该技巧,但问题是,它实际上打印的不是内容中的每个状态。我想OP想要的是,如果没有找到任何一个,就只打印“未找到”。@paxdiablo,哦,我现在明白他的意思了。在列表中搜索一个项目是一种非常常见的算法,在网上的许多地方都可以找到。在这里发帖之前,请先研究一下主题。这能回答你的问题吗?
result = [status.decode() for status in status_type if status in content]
if len(result) == 0:
   print("Not Found")
else:
   for status in result:
       print(status)