找出列表中每个项目的对象类型的最佳方法是什么?
我一直在使用下面但它非常麻烦,并且需要知道对象类型以便能够测试它。
for form in form_list:
if type(form) is list:
print 'it is a list'
else:
print 'it is not a list'
if type(form) is dict:
print 'it is a dict'
else:
print 'it is not a dict'
if type(form) is tuple:
print 'it is a tuple'
else:
print 'it is not a tuple'
if type(form) is str:
print 'it is a string'
else:
print 'it is not a string'
if type(form) is int:
print 'it is an int'
else:
print 'it is not an int'
答案 0 :(得分:3)
在Python 2.7中:
form_list = ['blah', 12, [], {}, 'yeah!']
print map(type, form_list)
[str, int, list, dict, str]
在Python 3.4中:
form_list = ['blah', 12, [], {}, 'yeah!']
print(list(map(type, form_list)))
[<class 'str'>, <class 'int'>, <class 'list'>, <class 'dict'>, <class 'str'>]
答案 1 :(得分:1)
知道python中的类型通常不是理想的方式。如果您对此不熟悉,请阅读duck-typing
主题。
如果您仍想沿着这条路走下去,请执行以下操作:
objtype = type(form)
if objtype is list:
#do stuff
elif objtype is str:
#do other stuff
else:
#can't handle this
等等