Python list.index 在找不到索引时抛出异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/674229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python list.index throws exception when index not found
提问by Joan Venge
Why does list.index throw an exception, instead of using an arbitrary value (for example, -1
)? What's the idea behind this?
为什么 list.index 会抛出异常,而不是使用任意值(例如,-1
)?这背后的想法是什么?
To me it looks cleaner to deal with special values, rather than exceptions.
对我来说,处理特殊值而不是异常看起来更干净。
EDIT: I didn't realize -1
is a potentially valid value. Nevertheless, why not something else? How about a value of None?
编辑:我没有意识到-1
是一个潜在的有效值。尽管如此,为什么不做其他事情呢?None 的值怎么样?
采纳答案by Devin Jeanpierre
Because -1
is itself a valid index. It could use a different value, such as None
, but that wouldn't be useful, which -1
can be in other situations (thus str.find()
), and would amount simply to error-checking, which is exactly what exceptions are for.
因为-1
本身就是一个有效的索引。它可以使用不同的值,例如None
,但这不会有用,这-1
可能在其他情况下(因此str.find()
),并且仅相当于错误检查,这正是异常的用途。
回答by vartec
Well, the special value would actually have to be None
, because -1 is a valid index (meaning the last element of a list).
好吧,特殊值实际上必须是None
,因为 -1 是有效索引(意味着列表的最后一个元素)。
You can emulate this behavior by:
您可以通过以下方式模拟此行为:
idx = l.index(x) if x in l else None
回答by amit
To add to Devin's response: This is an old debate between special return values versus exceptions. Many programming gurus prefer an exception because on an exception, I get to see the whole stacktrace and immediate infer what is wrong.
补充一下 Devin 的回答:这是特殊返回值与异常之间的古老争论。许多编程大师更喜欢异常,因为在异常中,我可以看到整个堆栈跟踪并立即推断出问题所在。
回答by John Fouhy
The "exception-vs-error value" debate is partly about code clarity. Consider code with an error value:
“异常与错误值”的争论部分是关于代码清晰度的。考虑带有错误值的代码:
idx = sequence.index(x)
if idx == ERROR:
# do error processing
else:
print '%s occurred at position %s.' % (x, idx)
The error handling ends up stuffed in the middle of our algorithm, obscuring program flow. On the other hand:
错误处理最终被塞在我们算法的中间,模糊了程序流程。另一方面:
try:
idx = sequence.index(x)
print '%s occurred at position %s.' % (x, idx)
except IndexError:
# do error processing
In this case, the amount of code is effectively the same, but the main algorithm is unbroken by error handling.
在这种情况下,代码量实际上是相同的,但主要算法不受错误处理的影响。
回答by Jason Baker
It's mainly to ensure that errors are caught as soon as possible. For example, consider the following:
主要是为了确保尽快发现错误。例如,请考虑以下情况:
l = [1, 2, 3]
x = l.index("foo") #normally, this will raise an error
l[x] #However, if line 2 returned None, it would error here
You'll notice that an error would get thrown at l[x]
rather than at x = l.index("foo")
if index were to return None. In this example, that's not really a big deal. But imagine that the third line is in some completely different place in a million-line program. This can lead to a bit of a debugging nightmare.
您会注意到,如果 index 返回 None l[x]
,x = l.index("foo")
则会抛出错误而不是 at 。在这个例子中,这并不是什么大问题。但是想象一下,在百万行程序中,第三行在某个完全不同的地方。这可能会导致一些调试噩梦。
回答by Phil H
In Python, -1 is a valid index, meaning a number from the end of the list (instead of the beginning), so if you were to do
在 Python 中,-1 是一个有效的索引,意思是从列表末尾(而不是开头)开始的数字,所以如果你要这样做
idx = mylist.index(someval)
nextval = mylist[idx+1]
then you would get the first value of the array, instead of realising there was an error. This way you can catch the exception and deal with it. If you don't want exceptions, then just check beforehand:
然后你会得到数组的第一个值,而不是意识到有错误。这样你就可以捕获异常并处理它。如果您不想要异常,那么只需事先检查:
if someval in mylist:
idx = mylist.index(someval)
Edit: There's not really any point in returning None, because if you're going to test for None, you might as well test whether the value is in the list as above!
编辑:返回 None 没有任何意义,因为如果您要测试 None,您不妨测试该值是否在上面的列表中!
回答by MarkusQ
I agree with Devin Jeanpierre, and would add that dealing with special values may look good in small example cases but (with a few notable exceptions, e.g. NaN in FPUs and Null in SQL) it doesn't scale nearly as well. The only time it works is where:
我同意 Devin Jeanpierre 的观点,并补充说,处理特殊值在小示例情况下可能看起来不错,但是(除了一些值得注意的例外,例如 FPU 中的 NaN 和 SQL 中的 Null)它几乎不能扩展。它唯一有效的地方是:
- You've typically got lots of nested homogeneous processing (e.g. math or SQL)
- You don't care about distinguishing error types
- You don't care where the error occurred
- The operations are pure functions, with no side effects.
- Failure can be given a reasonable meaning at the higher level (e.g. "No rows matched")
- 您通常有很多嵌套的同类处理(例如数学或 SQL)
- 你不在乎区分错误类型
- 你不在乎错误发生在哪里
- 操作是纯函数,没有副作用。
- 失败可以在更高级别给出合理的含义(例如“没有匹配的行”)
回答by recursive
It's a semantic argument. If you want to know the index of an element, you are claiming that it already exists in the list. If you want to know whether or not it exists, you should use in
.
这是一个语义论证。如果你想知道一个元素的索引,你就声称它已经存在于列表中。如果你想知道它是否存在,你应该使用in
.
回答by gimel
One simple idea: -1
is perfectly usable as an index (as are other negative values).
一个简单的想法:-1
完全可以用作索引(与其他负值一样)。
回答by Mawg says reinstate Monica
def GetListIndex(list, searchString):
try:
return list.index(searchString)
except ValueError:
return False
except Exception:
raise