2016-02-26 26 views
1

使用逗號和明確爆炸索引引用可能更傳統的讀者之間有性能差異嗎?因爲似乎都產生相同的結果,但後者可能會更直觀一些蟒蛇numpy切片符號(COMMA VS標準索引)

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

幾乎總是去的逗號,不是因爲性能原因,而是因爲索引兩次是不太相同的:

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 

我不知道這是怎麼回事最慢的運行,並具有這樣的時間差,跑的最快。

+0

是否有指向文檔的鏈接,詳細說明您在逗號和索引之間提及的兩次之前的區別?谷歌搜索'逗號與索引'不完全是最具描述性的解決方案 – AlanSTACK

+1

@AlanL:我不知道描述它的文檔頁面,但它是基本索引規則的直接結果。在'x [:1,:1]'中,索引表達式表示沿着'x'的第一個和第二個軸切片。相反,'x [:1] [:1]'表示沿着'x'的第一個軸切片,然後沿結果的第一個軸切片。 – user2357112

0

第二種情況效率較低,因爲在隨後編入索引的第一個索引後創建了新的臨時數組。