Python list.index在找不到索引时抛出异常 [英] Python list.index throws exception when index not found
问题描述
为什么list.index抛出异常,而不是使用任意值(例如, -1
)?这背后的想法是什么?
Why does list.index throw an exception, instead of using an arbitrary value (for example, -1
)? What's the idea behind this?
对我来说,处理特殊值而不是例外情况看起来更干净。
To me it looks cleaner to deal with special values, rather than exceptions.
编辑:我没有意识到 -1
是一个潜在有效的值。不过,为什么不是别的呢?无价值怎么样?
EDIT: I didn't realize -1
is a potentially valid value. Nevertheless, why not something else? How about a value of None?
推荐答案
因为 -1
本身就是有效的索引。它可以使用不同的值,例如无
,但这没有用, -1
可以是在其他情况下(因此 str.find()
),并且仅仅是错误检查,这正是例外情况。
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.
这篇关于Python list.index在找不到索引时抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!