8

拡張インデックス構文は、python のドキュメントに記載されています。

slice([start], stop[, step])

拡張インデックス構文を使用すると、スライス オブジェクトも生成されます。例:a[start:stop:step]またはa[start:stop, i]. itertools.islice()イテレータを返す別のバージョンについては、を参照してください。

a[start:stop:step]説明どおりに動作します。しかし、2番目のものはどうですか?どのように使用されますか?

4

2 に答える 2

12

a[start:stop,i] calls the method a.__getitem__((slice(start,stop,None), i)).

This raises a TypeError if a is a list, but it is valid and useful notation if a is a numpy array. In fact, I believe the developers of Numpy asked the developers of Python to extend valid Python slicing notation precisely so that numpy array slicing notation could be implemented more easily.

For example,

import numpy as np
arr=np.arange(12).reshape(4,3)
print(arr)
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]]

1:3 selects rows 1 and 2, and the 2 selects the third column:

print(arr[1:3,2])
# [5 8]

PS. To experiment with what slice is getting sent to __getitem__, you can play around with this toy code:

class Foo(list):
    def __getitem__(self,key):
        return repr(key)

foo=Foo(range(10))
print(foo[1:5,1,2])
# (slice(1, 5, None), 1, 2)
于 2010-05-03T20:47:55.700 に答える
4

この表記は、多次元配列[:,:]をスライスするために使用されます。Pythonにはデフォルトで多次元配列がありませんが、構文はそれをサポートしており、たとえばnumpyはこの構文を利用しています。

于 2010-05-03T20:34:32.967 に答える