有人可以向我解释funcion list.index()的功能吗?我有以下代码:Python:list.index找不到现有的元素
def getPos(self,tile):
print self.tiles[5][5]
print tile
try:
myIndex = self.tiles.index(tile)
#some code
except:
print "exception raised"
#some code
结果:
<Tile.Tile instance at 0x36BCEB8>
<Tile.Tile instance at 0x36BCEB8>
exception raised
你有一个想法,为什么list.index()返回一个例外,虽然瓷砖变量是瓷砖的元素[引用] []?非常感谢。
PS:顺便说一句我传递瓦片[5] [5]在该特定情况下
作为一个方面:绝不要使用裸露的'except:' - 对于你想要捕捉的异常,一定要具体说明,否则你可能会捕获一些你并不期望的东西。 –
想一想这件事。如果'some_list.index(some_item)'返回'i',那么'some_list [i]'应该返回'some_item'。你在'index'调用之后期待'myIndex'是什么?如果它能够工作,你需要能够说'self.tiles [myIndex]'。但是,显然没有'myIndex'可以完成这项工作。所以'self.tile.index(tile)'不能指望工作。 – Ben