给出numpy数组a
import numpy as np
a = np.arange(5)
如何获取包含a的所有数据属性但不包含方法属性的列表?
# expected to be part of list
a.shape
a.size
a.ndim
# expected NOT to be part of list
a.sum()
a.all()
a.max()
答案 0 :(得分:2)
import numpy as np
a = np.arange(5)
attribute_list = [attribute for attribute in dir(a) if not callable(getattr(a, attribute))]
output: ['T', '__array_finalize__', '__array_interface__', '__array_priority__', '__array_struct__', '__doc__', '__hash__', 'base', 'ctypes', 'data', 'dtype', 'flags', 'flat', 'imag', 'itemsize', 'nbytes', 'ndim', 'real', 'shape', 'size', 'strides']
如果要避免使用受保护的属性:
attribute_list = [attribute for attribute in dir(a) if not callable(getattr(a, attribute)) and attribute[0] != '_']
output: ['T', 'base', 'ctypes', 'data', 'dtype', 'flags', 'flat', 'imag', 'itemsize', 'nbytes', 'ndim', 'real', 'shape', 'size', 'strides']