错误:在列表交换期间列表索引超出范围



嗨,我已经运行了这段代码,它对前2个列表有效,但在第三个列表中出现了错误,下面是代码:

    b = [[1,2],[3,4],[5,6]]
    c = [1, 1, 2]
    for i, item in enumerate(c):
        target_i = (i + 1) % 3
        temp = b[i][item]
        b[i][item] = b[target_i][item]
        b[target_i][item] = temp
        print(b)

,这是输出:

    [[1, 4], [3, 2], [5, 6]]
    [[1, 4], [3, 6], [5, 2]]
    Traceback (most recent call last):
    File "C:/Python34/LEARN/play/dapatkan_index2.py", line 7, in <module>
    temp = b[i][item]
    IndexError: list index out of range

您可能应该在之前添加检查,看看迭代值是否低于列表b的长度。您应该这样做

 for i, item in enumerate(c):
    if i < len(b):
       if item < len(b[i]):
          <your code>
    else : 
       pass

如果i (c的列表索引)或c[i]的值大于列表索引的值,则会得到此错误。在这里的else语句中,我刚刚给出了一个pass语句,但是您必须弄清楚代码需要什么并添加它。

由于c包含1, 2中的值,因此语句b[i][item]将索引到b[0][1], b[0][2],…等。要修复,您可能打算使用b[i][item - 1],或者更改c中的值。

最新更新