how to access elements in a 2D array?

后端 未结 6 1838
南旧
南旧 2020-11-29 08:49

I am new to python and I would like to understand how one goes about manipulating the elements of an array. If I have for example:

a= ( a11 a12 a13 )  and b          


        
相关标签:
6条回答
  • 2020-11-29 08:55

    a[1][1] does work as expected. Do you mean a11 as the first element of the first row? Cause that would be a[0][0].

    0 讨论(0)
  • 2020-11-29 08:59

    If you have

    a=[[1,1],[2,1],[3,1]]
    b=[[1,2],[2,2],[3,2]]
    

    Then

    a[1][1]
    

    Will work fine. It points to the second column, second row just like you wanted.

    I'm not sure what you did wrong.

    To multiply the cells in the third column you can just do

    c = [a[2][i] * b[2][i] for i in range(len(a[2]))] 
    

    Which will work for any number of rows.

    Edit: The first number is the column, the second number is the row, with your current layout. They are both numbered from zero. If you want to switch the order you can do

    a = zip(*a)
    

    or you can create it that way:

    a=[[1, 2, 3], [1, 1, 1]]
    
    0 讨论(0)
  • 2020-11-29 08:59

    Look carefully how many brackets does your array have. I met an example when function returned answer with extra bracket, like that:

    >>>approx
    array([[[1192,  391]],
           [[1191,  409]],
           [[1209,  438]],
           [[1191,  409]]])
    

    And this didn't work

    >>> approx[1,1]
    IndexError: index 1 is out of bounds for axis 1 with size 1
    

    This could open the brackets:

    >>> approx[:,0]
    array([[1192,  391],
           [1191,  409],
           [1209,  438],
           [1191,  409]])
    

    Now it is possible to use an ordinary element access notation:

    >>> approx[:,0][1,1]
    409
    
    0 讨论(0)
  • 2020-11-29 09:01

    If you want do many calculation with 2d array, you should use NumPy array instead of nest list.

    for your question, you can use:zip(*a) to transpose it:

    In [55]: a=[[1,1],[2,1],[3,1]]
    In [56]: zip(*a)
    Out[56]: [(1, 2, 3), (1, 1, 1)]
    In [57]: zip(*a)[0]
    Out[57]: (1, 2, 3)
    
    0 讨论(0)
  • 2020-11-29 09:09

    If you have this :

    a = [[1, 1], [2, 1],[3, 1]]
    

    You can easily access this by using :

    print(a[0][2])
    a[0][1] = 7
    print(a)
    
    0 讨论(0)
  • 2020-11-29 09:16

    Seems to work here:

    >>> a=[[1,1],[2,1],[3,1]]
    >>> a
    [[1, 1], [2, 1], [3, 1]]
    >>> a[1]
    [2, 1]
    >>> a[1][0]
    2
    >>> a[1][1]
    1
    
    0 讨论(0)
提交回复
热议问题