[英]Python: list.index fails to find existing element
Can someone explain to me how the funcion list.index() functions? 有人可以向我解释一下funcion list.index()的功能吗? I have the following code:
我有以下代码:
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
The result: 结果:
<Tile.Tile instance at 0x36BCEB8>
<Tile.Tile instance at 0x36BCEB8>
exception raised
Do you have an idea why list.index() returns an exception although the tile variable is a reference to an element of tiles[][] ? 您是否知道为什么list.index()会返回异常,尽管tile变量是对tiles [] []元素的引用? Thanks a lot.
非常感谢。
ps: btw I'm passing tiles[5][5] in this specific case ps:顺便说一下,在这种特殊情况下,我正在通过瓷砖[5] [5]
self.tiles
appears to be a sequence (eg list or tuple) of sequences. self.tiles
似乎是序列的序列(例如列表或元组)。 Elements of self.tiles
are sequences, not tiles. self.tiles
元素是序列,而不是tile。
self.tiles.index(tile)
tries to find a sequence which equals tile
, and fails. self.tiles.index(tile)
试图找到一个等于tile
的序列,然后失败。
Try instead: 尝试改为:
def getPos(self,tile):
for i,row in enumerate(self.tiles):
for j,elt in enumerate(row):
if tile == elt:
return (i,j)
raise ValueError('no tile found')
While the element does exist, it is not directly a member of tiles
: 虽然元素确实存在,但它不是
tiles
的成员:
tiles
is a two-dimensional list (a list of lists). tiles
是一个二维列表(列表列表)。 tiles[5]
is a list of Tile
s. tiles[5]
是Tile
的列表。 tiles[5][5]
is a single Tile
. tiles[5][5]
是单个Tile
。 Python does not recursively descend into a multidimensional list to find the element you're looking for. Python不会递归地下降到多维列表中以查找您正在查找的元素。 Therefore
tiles.index(tile)
fails; 因此
tiles.index(tile)
失败; tiles[5].index(tile)
would work. tiles[5].index(tile)
可以工作。
To illustrate: 为了显示:
>>> l = [[1,2], [3,4]]
>>> l.index(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 4 is not in list
>>> l[1].index(4)
1
How come tiles[5][5] and tile points to the same instance? tile [5] [5]和tile如何指向同一个实例? It appears to me that you grab entire this object at tile[5][5] as tile and try to locate it as an element of it.
在我看来,你在tile [5] [5]中抓取整个这个对象作为tile并尝试将其定位为它的元素。 dont understand your intention
不明白你的意图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.