要查找列表中项目的索引,可以使用:
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.
这对我来说似乎有点奇怪,如果找不到该项目,它会抛出错误。我来自(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
我使用 -1 表示未找到该项目。有什么更好的方法可以做到这一点,为什么 Python 没有内置这样的东西呢?
a = [1]
try:
index_value = a.index(44)
except ValueError:
index_value = -1
这个怎么样?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)