Python索引超出范围错误

时间:2015-11-01 09:30:27

标签: python loops debugging indexing

不确定为什么我的索引超出范围错误。

函数应循环ip列表,直到事件值结束:

event = ["Birthday-venues", "baby-shower", "wedding", "corp", "party"]
ip = [1, 2, 3]

lip = len(ip)
levent = len(event)


def eventIP():
    i = 0
    dict = {}
    while i < levent:
        for j in range(0, lip):
            dict[event[i]] = ip[j]
            if i < levent:
                i += 1
            else:
                break

    print(dict)

eventIP()

错误:

Traceback (most recent call last):
  File "script.py", line 21, in <module>
    eventIP()
  File "script.py", line 13, in eventIP
    dict[event[i]] = ip[j]
IndexError: list index out of range

1 个答案:

答案 0 :(得分:2)

崩溃是因为你在更新它之前测试我是否小于levent。请尝试以下方法:

    i += 1
    if i >= levent:
        break