问题描述
为什么 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.
EDIT:我没有意识到 -1
是一个潜在的有效值.尽管如此,为什么不做其他事情呢?None 的值怎么样?
EDIT: I didn't realize -1
is a potentially valid value. Nevertheless, why not something else? How about a value of None?
推荐答案
因为 -1
本身就是一个有效的索引.它可以使用不同的值,例如 None
,但这没有用,-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 在找不到索引时抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!