python numpy切片表示法(COMMA VS STANDARD INDEX)

时间:2016-02-26 06:18:16

标签: python numpy slice comma notation

使用逗号和明确地为更传统的读者引用索引引用之间是否存在性能差异?因为两者似乎产生相同的结果,但后者可能更直观一些

x = numpy.array([[1,2,3,4],
                 [5,6,7,8]])

comma_method = x[0,1:3] 
>>> numpy.array([2,3])

conventional method = x[0][1:3]
>>> numpy.array([2,3])

2 个答案:

答案 0 :(得分:3)

几乎总是使用逗号,不是出于性能原因,而是因为索引两次并不完全相同:

In [2]: x = numpy.array([[0, 1], [2, 3]])

In [3]: x[:1, :1]
Out[3]: array([[0]])

In [4]: x[:1][:1]
Out[4]: array([[0, 1]])

也就是说,逗号似乎也具有速度优势:

In [7]: %timeit x[0][0]
The slowest run took 25.41 times longer than the fastest. This could mean that a
n intermediate result is being cached 
1000000 loops, best of 3: 357 ns per loop

In [8]: %timeit x[0, 0]
The slowest run took 41.92 times longer than the fastest. This could mean that a
n intermediate result is being cached 
1000000 loops, best of 3: 148 ns per loop

我不确定最慢的跑步和跑得最快的跑步有什么不同。

答案 1 :(得分:0)

第二种情况效率较低,因为在随后索引的第一个索引之后创建了一个新的临时数组。