在python中处理list.index(可能不存在)的最佳方法是什么? [英] Best way to handle list.index(might-not-exist) in python?
问题描述
thing_index = thing_list.index(thing)
otherfunction( thing_list,thing_index)
好吧,这是简化的,但你明白了。现在 我可以这样做: 但是这感觉很脏,再加上我不知道 是否有一个更清晰的方法来实现相同的事情?假设列表没有排序。 使用try-except子句没有什么脏这是pythonic的方式。 回答评论: I have code which looks something like this: ok so that's simplified but you get the idea. Now I could do this: But this feels dirty, plus I don't know if Is there a cleaner way to achieve the same thing? Let's assume the list isn't sorted. There is nothing "dirty" about using try-except clause. This is the pythonic way. To answer the comment: 这篇关于在python中处理list.index(可能不存在)的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! thing
可能实际上不在列表中,在这种情况下,我想以 thing_index
的形式传递-1。在其他语言中,如果找不到元素,则返回 ValueError
。
try:
thing_index = thing_list.index(thing)
除了ValueError:
thing_index = -1
otherfunction(thing_list ,thing_index)
ValueError
可能因其他原因而被引发。我想出了以下基于生成器函数的解决方案,但它似乎有点复杂:
thing_index =([(i for我在xrange(len(thing_list))如果thing_list [i] == thing)]或[-1])[0]
ValueError
将仅由 .index
方法引发,因为它是您在那里唯一的代码!
在Python中, 更容易要求原谅而不是获得许可 理念已经确立, no index
不会引发任何其他问题的这种类型的错误。不是我能想到的。 thing_index = thing_list.index(thing)
otherfunction(thing_list, thing_index)
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
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]
ValueError
will be raised by the .index
method only, because it's the only code you have there!
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.