[英]I am getting IndexError: list index out of range
Error 错误
File "D:/hotel2.py", line 11, in addGuest guests[i].append(name) IndexError: list index out of range 在addGuest客人[i] .append(name)IndexError:列表索引超出范围时,文件“ D:/hotel2.py”第11行
hotel2.py hotel2.py
def addGuest():
i = 0
j = 0
global guestid
name = input("Please enter guest name:\n")
guests[i].append(name)
guests[j].append(guestid)
print("Guest %s has been created with guest ID: %d" % (guests[i], guests[j]))
i += 1
j += 1
guestid += 1
What I really want to do is store guestid
and guestname
in a way that I can display the guestname
when I enter guestid
. 我真正想要做的是存储guestid
和guestname
中,我可以显示的方式guestname
,当我进入guestid
。 But this function is not letting me do it. 但是此功能不允许我这样做。
You better use dictionary for key:value
pairs than two lists: 最好将字典用于key:value
对,而不要使用两个列表:
guestid2name = {}
def addGuest():
name = raw_input('enter guest name:\n')
global guestid
guestid2name[guestid] = name
print("Guest %s has been created with guest ID: %d" % (name, guestid))
This will create guestid2name
data structure of guestid's with the guest's name as value. 这将创建以访客的名字为值的guestid的guestid2name
数据结构。 It is much more efficient than using two distinct lists to achieve the same thing. 它比使用两个不同的列表来完成同一件事要高效得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.