0

我有这个代码:

level = {0, 0, 0,
         0, 1, 0,
         0, 0, 0}

class player:
    def getPlayerLoc(self, level):
        for i in level:
            if level[level.index(i)] == 1:
                print "Player location = " + str(i)


p1 = player()
p1.getPlayerLoc(level)

当我运行它时,它说:

Traceback (most recent call last):
  File "gamy.py", line 13, in <module>
    p1.getPlayerLoc(level)
  File "gamy.py", line 8, in getPlayerLoc
    if level[level.index(i)] == 1:
AttributeError: 'set' object has no attribute 'index'

看起来它正在将我的数组转换为一个集合对象。为什么会这样,我该如何解决?

4

1 回答 1

3
level = {0, 0, 0,
         0, 1, 0,
         0, 0, 0}

{}括号表示set,将其声明为list

level = [0, 0, 0,
         0, 1, 0,
         0, 0, 0]

例如

>>> level = {0, 0, 0,
         0, 1, 0,
         0, 0, 0}
>>> level
{0, 1}  # because set only contains unique elements

>>> level = [0, 0, 0,
         0, 1, 0,
         0, 0, 0]
>>> level
[0, 0, 0, 0, 1, 0, 0, 0, 0]
于 2012-05-28T18:06:47.193 回答