列表赋值超出索引范围
我有一个程序,它把字典的键分配给一个数组(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
使用 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())
如果你觉得有挑战,可以试试 列表推导式。
不过,你很快会发现另一个问题:
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'
我就不多说了,你自己来解决吧。
1
addr = []
这行代码创建了一个空列表,也就是里面没有任何元素。所以,addr[0] 这个位置是不存在的,如果你试图往这个不存在的位置存东西,就会出现一个叫做 IndexError 的错误。你可以试试用 addr.append(key)
来添加元素。
另外,不用像 FORTRAN 那样用索引 j 的循环,你可以用更符合 Python 风格的方法,一步就创建并初始化这个列表:
addr = list(clnts.keys())
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
时也需要这样做。
你的代码还有一些其他问题,这些问题不是你提问的重点;我猜这些只是你在简化示例时出现的错误。