numpy:a [i] [j]和a [i,j]之间的差异 [英] Numpy: Difference between a[i][j] and a[i,j]
问题描述
来自Python的Lists背景以及C ++/Java等编程语言的背景,人们习惯于使用a[i][j]
方法提取元素.但是在NumPy
中,通常会执行a[i,j]
.两者都会返回相同的结果.
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. But in NumPy
, one usually does a[i,j]
. Both of these would return the same result.
两者之间的根本区别是什么?应该优先选择哪个?
What is the fundamental difference between the two and which should be preferred?
推荐答案
主要区别在于a[i][j]
首先在a[i]
上创建一个视图,然后在该视图中建立索引.另一方面,a[i,j]
直接索引到a
中,从而使其更快:
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.
这篇关于numpy:a [i] [j]和a [i,j]之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!