gpt4 book ai didi

python - 找出列表中每个项目的对象类型的最佳方法

转载 作者:太空宇宙 更新时间:2023-11-04 10:21:35 24 4
gpt4 key购买 nike

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

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com