【问题标题】:Python3, If one of the items in the list found "print it" else print "not found"Python3,如果找到列表中的一项“打印它”,否则打印“未找到”
【发布时间】:2020-10-06 02:57:12
【问题描述】:

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

我的脚本:

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")

我的脚本的输出:

【问题讨论】:

  • 一个对象要么在列表中,要么不在列表中。所以你的第二个语句应该使用elif 而不是if
  • @Noah,实际上一个没有条件的else 也可以做到这一点,但问题实际上是它打印了 not found for each 状态不在内容中。我认为 OP 所追求的是仅在找到 none 时才打印 not found。
  • @paxdiablo ,哦,我明白他的意思了。
  • 在列表中搜索一个项目是一种非常常见的算法,在网上很多地方都可以使用。请在此处发布问题之前研究该主题。
  • 这能回答你的问题吗? How can you search for an item in a list - python

标签: python python-3.x list beautifulsoup


【解决方案1】:

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

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")

【讨论】:

    【解决方案2】:

    paxdiablo's answer 的标志方法可能是最直接的;另一种方法是将找到的状态收集在一个列表中,然后处理它:

    found_statuses = [status.decode() for status in status_type if status in content]
    
    if found_statuses:
        print(', '.join(found_statuses))
    else:
        print('Not Found')
    

    如果您需要在发现多个状态并且需要在这种情况下打印它们(或以其他方式打印它们)时需要采取特殊操作,这将特别有用:

    found_statuses = [status.decode() for status in status_type if status in content]
    
    if len(found_statuses) == 1:
        print(found_statuses[0])
    elif len(found_statuses) > 1:
        print("Conflicting statuses: %s" % ' and '.join(found_statuses))
    else:
        print('Not Found')
    

    【讨论】:

      【解决方案3】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多