【问题标题】:How to use If/Then with IndexError如何将 If/Then 与 IndexError 一起使用
【发布时间】:2020-04-14 12:56:16
【问题描述】:

该程序正在使用网站的 API 来获取最新的销售信息。该计划适用于最近销售的产品,但不适用于最近一天内没有销售的产品。

数组是 [],我当然会得到 IndexError: list index is out of range。

这是我的代码:

import requests

cybersole_url = 'https://www.botbroker.io/bots/6/chart?key_type=lifetime&days=1'
response = requests.get(cybersole_url)
response.raise_for_status()
if (response.json()[0][1] == None):
    cyber = "No recent sales."
else:
    cyber = "$" + str(response.json()[0][1])

如何解决此错误以获取 if 语句中列出的两个结果之一?我相信我使用了 try 和 except,但它只执行 except,即使它在数组中有对象。

【问题讨论】:

    标签: python python-3.x discord.py


    【解决方案1】:
    import requests
    
    cybersole_url = 'https://www.botbroker.io/bots/6/chart?key_type=lifetime&days=1'
    response = requests.get(cybersole_url)
    response.raise_for_status()
    
    # Try to index the result, otherwise set result=None
    try:
        result = response.json()[0][1]
    except IndexError:
        result = None
    
    cyber = 'No recent sales.' if not result else f'${result}'
    

    请注意,您可能需要添加另一层尝试捕获,因为您不仅要抓取[0] 处的元素,还要抓取[0][1] 处的元素——这里有两层索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      相关资源
      最近更新 更多