我想寫一個對象,它允許索引numpy數組的第一個維度,並應防止任何其他索引。索引在Numpy中的特定維度,並防止索引任何其他
import numpy as np
class Foo:
"""
Object that allows indexing the first dimension of arr
"""
def __getitem__(self, my_slice):
arr = np.arange(12).reshape((3, 4))
return arr[my_slice]
foo = Foo()
# Valid usages:
foo[0] # first row of arr
foo[:2] # two first rows of arr
foo[[0, 2]] # rows 0 and 2 of arr
# Invalid usages that must raise an Exception but are currently not:
foo[0, 0]
foo[..., 0]
foo[np.newaxis]
foo[[0,2], [0]]
foo[[[0,2], [0]]]
foo[[0,2, np.newaxis]]
根據以上(arr[my_slide]
)的解決方案,有效的情況下,通過(好),但無效的情況下,通得過(不好)。 __getitem__
爲了滿足所有要求要投入什麼?
「我正在嘗試編寫一個對象,該對象允許索引numpy數組的第一個維度,並且應該防止任何其他索引。」 - 你爲什麼想這樣做?你關心他們是否做了像'foo [:] [:,0]'? – user2357112
我關心,因爲我實際上索引幾個數組。所有這些數組的第一維具有相同的含義,因此索引它們是有意義的,但其他維度具有不同的含義。索引這些其他維度會產生可怕的錯誤。 –