简体   繁体   中英

Python: list.index fails to find existing element

Can someone explain to me how the funcion list.index() functions? 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[][] ? Thanks a lot.

ps: btw I'm passing tiles[5][5] in this specific case

self.tiles appears to be a sequence (eg list or tuple) of sequences. Elements of self.tiles are sequences, not tiles.

self.tiles.index(tile) tries to find a sequence which equals tile , and fails.

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 is a two-dimensional list (a list of lists).
  • tiles[5] is a list of Tile s.
  • tiles[5][5] is a single Tile .

Python does not recursively descend into a multidimensional list to find the element you're looking for. Therefore tiles.index(tile) fails; tiles[5].index(tile) would work.

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? 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. dont understand your intention

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM