【问题标题】:Index Error when passing a list to a class将列表传递给类时出现索引错误
【发布时间】:2017-06-26 06:43:22
【问题描述】:

我有以下代码:

class TestClass:

    def __init__(self, myint, mylist=None):

        if mylist == None:
            mylist = []
        self.myint = myint
        self.mylist = mylist[:]

theList = [[1,3,4,5,6],[1,2,3],[1],[1,2,3,4,5,6,7,8,9]]

myOb = []
for i in range(len(theList)):
    myOb[i] = TestClass(sum(theList[i]),theList[i])
    print(myOb[i].myint)
    print(myOb[i].mylist)

但是 __init__ 在 IndexError: list assignment index out of range 失败。这个我不明白。

有什么建议吗?

【问题讨论】:

  • 添加python 标签,以更好地限定您的问题。谢谢。

标签: python list class


【解决方案1】:

您可以添加:

myOb[0] = 1

在您定义它以理解之后 - myOb[i] = 在第一次迭代中尝试为第一个单元格 (i=0) 分配一些东西,但该单元格尚不存在(有 0 个单元格)。你想要的是:

myOb.append(TestClass(sum(theList[i]),theList[i]))

如果您正在构建 myOb 并且不需要打印,您可以使用:

myOb = map(lambda x: TestClass(sum(x),x), theList)

或列表理解。更好的是,在__init__ 中自己计算:

def __init__(self, mylist):
    ...
    self.myint = sum(mylist)

地图会变成:

myOb = map(TestClass, theList)

【讨论】:

    【解决方案2】:

    所以我的疏忽是该列表被声明为:

    myOb = [] 
    

    然后我继续尝试将元素添加到列表中。我应该附加它们。我已将代码更改为:

    myOb = []
    for i in range(len(theList)):
        myOb.append(TestClass(theList[i]))
        print(myOb[i].myint)
        print(myOb[i].mylist)
    

    现在我得到了正确的输出:

    19
    [1, 3, 4, 5, 6]
    6
    [1, 2, 3]
    1
    [1]
    45
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    所以那里。菜鸟错误。

    P.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-12
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多