简体   繁体   English

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

[英]python numpy slice notation (COMMA VS STANDARD INDEX)

Is there a performance difference between using a comma and explicitly exploding out the index references for perhaps more conventional readers?对于可能更传统的读者,使用逗号和显式展开索引引用之间是否存在性能差异? Since both seem to yield the same results but the latter may be more intuitive to some由于两者似乎产生相同的结果,但后者对某些人来说可能更直观

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])

Pretty much always go for the comma, not for performance reasons, but because indexing twice isn't quite equivalent:几乎总是使用逗号,不是出于性能原因,而是因为索引两次并不完全等效:

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]])

That said, the comma also appears to have a speed advantage:也就是说,逗号似乎也具有速度优势:

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

I'm not sure what's up with the slowest run and the fastest run having such a time difference.我不确定最慢的运行和最快的运行有这样的时差是怎么回事。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM