找出列表中每个项目的对象类型的最佳方法是什么?

我一直在使用下面的方法,但是它很麻烦,并且需要知道对象类型才能进行测试。

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'

最佳答案

在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'>]

关于python - 找出列表中每个项目的对象类型的最佳方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31946795/

10-16 06:08