列表分配超出索引

时间:2011-11-01 03:16:31

标签: python indexing

我有以下程序将字典键分配给数组(addr[]),并将值分配给相应的数组(msg[]

import smtplib  

class item:
    id = 0 # next available Item ID
    def __init__(self,startBid,desc):
        self.id = item.id
        item.id += 1
        self.highBid = startBid
        self.highBidder = None
        self.desc = desc
        self.isopen = True

item1 = item(200.30, "bike with a flat tire")
item2 = item(10.4, "toaster that is very large")
item3 = item(40.50, "computer with 8 gb of ram")

clnts = {'test@hotmail.com':[item1,item3], 'test@yahoo.com':[item2] }

def even(num):
    if (num % 2 == 0):
        return True
    else:
        return False

def getmsg(clnts):
    index = 0
    j = 0
    msg = []
    addr = []

    for key in clnts:
        addr[j] = key
        for key in values:
            msg[j] += str(key.highbidder()) + key.highbid()
            index += 1
            j += 1

getmsg(clnts)

我已经尝试过并尝试解决此问题,但我一直收到错误:

line 39, in getmsg
    addr[j] = key
IndexError: list assignment index out of range

3 个答案:

答案 0 :(得分:4)

在Python中,您无法分配到尚不存在的索引:

>>> x = []
>>> x[0] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

而不是

addr[j] = key

尝试

addr.append(key)

您可以完全取消j,因为您必须对msg执行相同操作。

您的代码还有一些其他问题不属于您的问题;我假设这些只是试图为一个问题制作一个简化示例的错误。

答案 1 :(得分:1)

addr = []创建一个没有元素的空列表。因此addr [0]不存在,并且尝试将任何内容存储到不存在的位置将生成IndexError。请改为addr.append(key)

或者不是使用带索引j的FORTRAN样式循环,而是可以使用更多Pythonic技术一步创建和初始化列表:

addr = list(clnts.keys())

答案 2 :(得分:0)

使用list.append()

def getmsg(clnts):

    msg = []
    addr = []

    for key in clnts:
        addr.append(key)

        for key in values:
            msg.append(str(key.highbidder()) + key.highbid())

如果您感到勇敢,请尝试list comprehensions


然而,你很快就会发现另一个问题:

NameError: global name 'values' is not defined

我猜你想要clnts中每个key对应的值:

def getmsg(clnts):

    msg = []
    addr = []

    for key in clnts:
        addr.append(key)

        for value in clnts[key]:
            msg.append(str(value.highbidder()) + value.highbid()) 

之后你会发现另一个问题:

AttributeError: item instance has no attribute 'highbidder'

我会让你从那里拿走它。