【问题标题】:Arrays in my class is giving me an error... AttributeError: 'set' object has no attribute 'index'我班级中的数组给了我一个错误... AttributeError: 'set' object has no attribute 'index'
【发布时间】:2012-05-28 18:03:03
【问题描述】:

我有这个代码:

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'

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

【问题讨论】:

  • 呃,那一个集合对象。您的意思是使用列表吗?

标签: python arrays compiler-errors set


【解决方案1】:
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]

【讨论】:

  • 哦,失败,我完全忘记了 xD 谢谢!
  • 啊,我不知道你能做到这一点XD
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
  • 2013-07-26
  • 1970-01-01
  • 2021-10-09
  • 2022-12-01
相关资源
最近更新 更多