Best way to handle list.index(might-not-exist) in python?(在python中处理list.index(可能不存在)的最佳方法?)
问题描述
我的代码看起来像这样:
I have code which looks something like this:
thing_index = thing_list.index(thing)
otherfunction(thing_list, thing_index)
好的,这很简单,但你明白了.现在 thing
可能实际上不在列表中,在这种情况下,我想将 -1 作为 thing_index
传递.在其他语言中,如果 index()
找不到元素,这就是您所期望的返回值.实际上它会抛出一个 ValueError
.
ok so that's simplified but you get the idea. Now thing
might not actually be in the list, in which case I want to pass -1 as thing_index
. In other languages this is what you'd expect index()
to return if it couldn't find the element. In fact it throws a ValueError
.
我可以这样做:
try:
thing_index = thing_list.index(thing)
except ValueError:
thing_index = -1
otherfunction(thing_list, thing_index)
但这感觉很脏,而且我不知道是否会因其他原因引发 ValueError
.我根据生成器函数想出了以下解决方案,但看起来有点复杂:
But this feels dirty, plus I don't know if ValueError
could be raised for some other reason. I came up with the following solution based on generator functions, but it seems a little complex:
thing_index = ( [(i for i in xrange(len(thing_list)) if thing_list[i]==thing)] or [-1] )[0]
有没有更简洁的方法来实现同样的目标?假设列表没有排序.
Is there a cleaner way to achieve the same thing? Let's assume the list isn't sorted.
推荐答案
使用 try-except 子句并没有什么脏".这是pythonic的方式.ValueError
将仅由 .index
方法引发,因为它是您那里唯一的代码!
There is nothing "dirty" about using try-except clause. This is the pythonic way. ValueError
will be raised by the .index
method only, because it's the only code you have there!
回答评论:
在 Python 中,请求宽恕比获得许可更容易 理念已经确立,no index
不会针对任何其他问题引发此类错误.不是我能想到的.
To answer the comment:
In Python, easier to ask forgiveness than to get permission philosophy is well established, and no index
will not raise this type of error for any other issues. Not that I can think of any.
这篇关于在python中处理list.index(可能不存在)的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在python中处理list.index(可能不存在)的最佳方法?


基础教程推荐
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01