可能重复:
Python list.index问题
要查找列表中项目的索引,请使用:
list.index(x)
Return the index in the list of the first item whose value is x.
It is an error if there is no such item.
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎有点奇怪,如果找不到该项目会引发错误.我来自(Objective-C land),它返回一个NSNotFound枚举(它只是一个max int,表示找不到该项).
所以我做了一些丑陋的事情来解决这个问题:
index = 0
for item in self.items:
if item.id == desired_id:
return index
index = index + 1
return -1
Run Code Online (Sandbox Code Playgroud)
我用-1来表示找不到该项目.有什么更好的方法可以做到这一点,为什么Python没有内置这样的东西?