幾乎總是去的逗號,不是因爲性能原因,而是因爲索引兩次是不太相同的:
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
我不知道這是怎麼回事最慢的運行,並具有這樣的時間差,跑的最快。
是否有指向文檔的鏈接,詳細說明您在逗號和索引之間提及的兩次之前的區別?谷歌搜索'逗號與索引'不完全是最具描述性的解決方案 – AlanSTACK
@AlanL:我不知道描述它的文檔頁面,但它是基本索引規則的直接結果。在'x [:1,:1]'中,索引表達式表示沿着'x'的第一個和第二個軸切片。相反,'x [:1] [:1]'表示沿着'x'的第一個軸切片,然後沿結果的第一個軸切片。 – user2357112