Numpy: Difference between a[i][j] and a[i,j]

后端 未结 1 1385
夕颜
夕颜 2021-02-13 05:09

Coming from a Lists background in Python and that of programming languages like C++/Java, one is used to the notation of extracting elements using a[i][j] approach.

1条回答
  •  长情又很酷
    2021-02-13 05:24

    The main difference is that a[i][j] first creates a view onto a[i] and then indexes into that view. On the other hand, a[i,j] indexes directly into a, making it faster:

    In [9]: a = np.random.rand(1000,1000)
    
    In [10]: %timeit a[123][456]
    1000000 loops, best of 3: 586 ns per loop
    
    In [11]: %timeit a[123,456]
    1000000 loops, best of 3: 234 ns per loop
    

    For this reason, I'd prefer the latter.

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