Simple python code about double loop

前端 未结 3 598
闹比i
闹比i 2021-01-20 16:04

I tested the following python code on Spyder IDE. Thinking it would output 2d array q as increasing number as 0..31 from q[0][0] to q[3][7]

3条回答
  •  梦毁少年i
    2021-01-20 16:14

    As explained the problem is caused due to * operation on lists, which create more references to the same object. What you should do is to use append:

    q=[]
    for i in range(4): 
        q.append([])
        for j in range(8): 
            q[i].append(8*i+j)
    print q 
    

    [[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30, 31]]

提交回复
热议问题