Simple python code about double loop

前端 未结 3 597
闹比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条回答
  • 2021-01-20 16:05

    When you do something like l = [x]*8 you are actually creating 8 references to the same list, not 8 copies.

    To actually get 8 copies, you have to use l = [[x] for i in xrange(8)]

    >>> x=[1,2,3]
    >>> l=[x]*8
    >>> l
    [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
    >>> l[0][0]=10
    >>> l
    [[10, 2, 3], [10, 2, 3], [10, 2, 3], [10, 2, 3], [10, 2, 3], [10, 2, 3], [10, 2, 3], [10, 2, 3]]
    >>> l = [ [x] for i in xrange(8)]
    >>> l
    [[[10, 2, 3]], [[10, 2, 3]], [[10, 2, 3]], [[10, 2, 3]], [[10, 2, 3]], [[10, 2, 3]], [[10, 2, 3]], [[10, 2, 3]]]
    >>> l[0][0] = 1
    >>> l
    [[1], [[10, 2, 3]], [[10, 2, 3]], [[10, 2, 3]], [[10, 2, 3]], [[10, 2, 3]], [[10, 2, 3]], [[10, 2, 3]]]
    
    0 讨论(0)
  • 2021-01-20 16:12
    q=[somelist]*4 
    

    creates a list with four identical items, the list somelist. So, for example, q[0] and q[1] reference the same object.

    Thus, in the nested for loop q[i] is referencing the same list regardless of the value of i.

    To fix:

    q = [[0]*8 for _ in range(4)]
    

    The list comprehension evaluates [0]*8 4 distinct times, resulting in 4 distinct lists.


    Here is a quick demonstration of this pitfall:

    In [14]: q=[[0]*8]*4
    

    You might think you are updating only the first element in the second row:

    In [15]: q[1][0] = 100
    

    But you really end up altering the first element in every row:

    In [16]: q
    Out[16]: 
    [[100, 0, 0, 0, 0, 0, 0, 0],
     [100, 0, 0, 0, 0, 0, 0, 0],
     [100, 0, 0, 0, 0, 0, 0, 0],
     [100, 0, 0, 0, 0, 0, 0, 0]]
    
    0 讨论(0)
  • 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]]

    0 讨论(0)
提交回复
热议问题