📅  最后修改于: 2023-12-03 15:24:35.339000             🧑  作者: Mango
在Python中,可以使用type()
函数来检查单个变量的类型。但是,如果您需要检查列表中所有元素的类型怎么办?本文将介绍几种方法来检查列表中的类型。
循环遍历列表,对于每个元素使用type()
函数来检查其类型。以下是一个示例代码:
my_list = [1, "hello", 3.4, (4+5j)]
for item in my_list:
print(type(item))
输出结果为:
<class 'int'>
<class 'str'>
<class 'float'>
<class 'complex'>
用列表解析式生成一个新的列表,其中每个元素都是原列表中对应位置元素的类型。以下是一个示例代码:
my_list = [1, "hello", 3.4, (4+5j)]
type_list = [type(item) for item in my_list]
print(type_list)
输出结果为:
[<class 'int'>, <class 'str'>, <class 'float'>, <class 'complex'>]
使用map()
函数,将type()
函数应用于列表中的每个元素。以下是一个示例代码:
my_list = [1, "hello", 3.4, (4+5j)]
type_list = list(map(type, my_list))
print(type_list)
输出结果为:
[<class 'int'>, <class 'str'>, <class 'float'>, <class 'complex'>]
本文介绍了三种方法来检查Python列表中的类型。无论您使用哪种方法,确保要始终检查您的代码来避免类型不匹配错误。