在一个对象中打印所有属性的类型是最佳方式吗?

2024-10-05 14:25:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了this post,它回答了这个问题,但我认为应该有一个更简单的方法来做到这一点

下面是我的例子:从对象boston,我想知道attibutes是字符串还是数组。 a) 告诉我名字。 b) 给我的显然不是我想要的信息 c) 给我想要的 但我认为选项c)过于复杂,应该有更干净的方法来做到这一点。有什么想法吗

from sklearn.datasets import *
boston = load_boston()

a= dir(boston)
b=[type(x) for x  in boston]
c=[type(getattr(boston, name)).__name__ for name in dir(boston) ]

print(a,"\n", b,"\n",c)

输出:

['DESCR', 'data', 'feature_names', 'filename', 'target'] 
[<class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>, <class 'str'>] 
['str', 'ndarray', 'ndarray', 'str', 'ndarray']

Tags: 对象方法nameinfortypedirthis
1条回答
网友
1楼 · 发布于 2024-10-05 14:25:18
print([x for x in boston])
print([type(boston[x]) for x in boston])

输出:

['data', 'target', 'feature_names', 'DESCR', 'filename']
[<class 'numpy.ndarray'>, <class 'numpy.ndarray'>, <class 'numpy.ndarray'>, <class 'str'>, <class 'str'>]

相关问题 更多 >