【问题标题】:How to return None if .index() got ValueError? [duplicate]如果 .index() 得到 ValueError,如何返回 None? [复制]
【发布时间】:2017-04-03 03:26:47
【问题描述】:
date_index = data['date'].index(input_date)

从上面的代码中,如果 input_date 在任何数据索引中都不匹配['date'],它将得到错误:

> ValueError: '99/99/9999' is not in list

但我想在得到 ValueError 时得到 None。 我已经尝试过使用

if data['date'].index(input_date) is None:
    return None
else:
    pass

但它不起作用。

谢谢。

【问题讨论】:

  • 为什么您认为if 会起作用?如果.index 返回None 你已经有None 要么try 并捕获错误或检查项目是否是in 列表优先。

标签: python python-3.x


【解决方案1】:

两种常见的处理方式:

data_index = data['date'].index(date_of_stock) if data['date'] else None

或者

try:
    data_index=data['date'].index(date_of_stock)
except ValueError:
   data_index=0

【讨论】:

    猜你喜欢
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2019-06-16
    • 2018-04-22
    • 1970-01-01
    • 2016-10-04
    相关资源
    最近更新 更多