私はこれがpythonicと見なされると思います:
for item in a[:3]:
print item
編集:ほんの数秒でこの答えが冗長になったので、私はいくつかの背景情報を提供しようとします:
配列スライシングにより、文字列のリストなどのシーケンスをすばやく選択できます。1次元シーケンスのサブシーケンスは、左端と右端のインデックスで指定できます。
>>> [1,2,3,4,5][:3] # every item with an index position < 3
[1, 2, 3]
>>> [1,2,3,4,5][3:] # every item with an index position >= 3
[4, 5]
>>> [1,2,3,4,5][2:3] # every item with an index position within the interval [2,3)
[3]
左側のエンドポイントは含まれていますが、右側のエンドポイントは含まれていないことに注意してください。3番目の引数を追加してn
、シーケンスのすべての要素のみを選択できます。
>>> [1,2,3,4,5][::2] # select every second item from list
[1, 3, 5]
>>> [1,2,3,4,5][::-1] # select every single item in reverse order
[5,4,3,2,1]
>>> [1,2,3,4,5][1:4:2] # every second item from subsequence [1,4) = [2,3,4]
[2, 4]
リストをnumpy配列に変換することで、多次元スライスを実行することも可能です。
>>> numpy.array([[1,2,3,4,5], [1,2,3,4,5]])[:, ::2]
array([[1, 3, 5],
[1, 3, 5]])