简体   繁体   English

我收到IndexError:列表索引超出范围

[英]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 . 我真正想要做的是存储guestidguestname中,我可以显示的方式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.

相关问题 为什么我收到 IndexError: list index out of range 这个函数? - Why am I getting IndexError: list index out of range for this function? 为什么我收到 IndexError: list index out of range - Why am I getting IndexError: list index out of range 为什么在此代码中出现IndexError:list index超出范围? - Why am I getting IndexError: list index out of range in this code? 当我的代码似乎在范围内时,为什么会出现 IndexError: list index out of range? - Why am I getting an IndexError: list index out of range when my code appears to be within the range? 为什么我得到 IndexError: list index out of range 错误,即使我有一个正确的列表 - Why am I getting IndexError: list index out of range error even though I have a proper list 为什么我收到此错误? twitter_list_dict.append(line [0])IndexError:列表索引超出范围 - why am I getting this error? twitter_list_dict.append(line[0]) IndexError: list index out of range 为什么收到此错误“ IndexError:字符串索引超出范围” - Why am I getting this Error “IndexError: string index out of range” 为什么会出现 IndexError:字符串索引超出范围? - Why am I getting an IndexError: string index out of range? 为什么在云上训练时会收到“IndexError: list index out of range”? - Why am I getting "IndexError: list index out of range" when training on the cloud? Python:不知道为什么会出现“ IndexError:列表分配索引超出范围”错误 - Python: not sure why I am getting “IndexError: list assignment index out of range” error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM