Python索引错误超出范围

时间:2017-05-30 13:25:24

标签: python-2.7

我需要为不同的部门分配座位,但是当我尝试这样做时,我会遇到错误。

下面我粘贴了代码:

#matrix for dept1
X = [111, 222, 333, 444, 555, 666, 777 ,888, 999, 123, 234,345]
#matrix for dept2
Y = [1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999,9876, 8765,7654]
#empty class room which consist of 18 students
class_room = [[0,0,0,0,0],
         [0,0,0,0,0],
        [0,0,0,0,0],
        [0,0,0,0,0],
        [0,0,0,0,0]]


ca = 0

pa = 0

print 'combining dept1 and dept2 in alternative manner'


for i in range(5):

    for j in range(25):

        if j%2 == 0:
            class_room[i][j] = X[pa]
            pa += 1
        else:
            class_room[i][j] = Y[ca]
            ca += 1

print class_room

#error - Traceback (most recent call last):
# File "C:\Users\SONY\workspace\mine\taest3.py", line 24, in <module>
#   class_room[i][j] = X[pa][pa]
#IndexError: list index out of range

请帮助我纠正和澄清。

1 个答案:

答案 0 :(得分:0)

你循环for j in range(25),但你没有25个元素长。相反,这样做:

for i in range(5):
    for j in range(5):  # DIFFERENT
        if (5 * i + j) % 2 == 0:  # ALSO DIFFERENT
            class_room[i][j] = X[pa]
            pa += 1
        else:
            class_room[i][j] = Y[ca]
            ca += 1

请注意,这会引入一个 new IndexError,因为您有25个教室,XY中只有24个参赛作品。将另一个元素添加到X,代码将运行。