python - 在python中处理list.index(可能不存在)的最佳方法?

标签 python list find indexing

我的代码看起来像这样:

thing_index = thing_list.index(thing)
otherfunction(thing_list, thing_index)

好的,这很简单,但你明白了。现在 thing 可能实际上不在列表中,在这种情况下,我想将 -1 作为 thing_index 传递。在其他语言中,如果 index() 找不到元素,这就是您所期望的返回值。实际上它会抛出一个 ValueError

我可以这样做:

try:
    thing_index = thing_list.index(thing)
except ValueError:
    thing_index = -1
otherfunction(thing_list, thing_index)

但这感觉很脏,而且我不知道是否会因其他原因引发 ValueError。我根据生成器函数想出了以下解决方案,但看起来有点复杂:

thing_index = ( [(i for i in xrange(len(thing_list)) if thing_list[i]==thing)] or [-1] )[0]

有没有更简洁的方法来实现同样的目标?假设列表没有排序。

最佳答案

使用 try-except 子句并没有什么“脏”。这是pythonic的方式。 ValueError 将仅由 .index 方法引发,因为它是您那里唯一的代码!

回复评论:
在 Python 中,easier to ask forgiveness than to get permission哲学已经确立,no index 不会针对任何其他问题引发此类错误。不是我能想到的。

关于python - 在python中处理list.index(可能不存在)的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2132718/

相关文章:

python - 如何避免使用 import 并仍然从函数中获得相同的输出?

linux - 无法使用 find -exec 运行源命令

MySQL查询查找已下0订单/无订单的客户

python - 使用 Celery 在集群中进行任务管理是个好主意吗?

python - Flask 领事和领事 DNS

python - 张量运算的导数

c# - System.ArgumentOutOfRangeException : 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'

python - 如何将 pandas 系列的列值转换为 Python 列表?

python - 在 Python 类中的何处建立数据库连接以运行多个查询?

ansible - 如何在ansible中仅发送文件路径?