在Python 3.6中,我需要确定列表中的哪些元素包含整数,浮点数或字符串。
当我使用“类型”函数时,它返回一个列表元素,但是该元素包含什么?字符串还是函数?
my_list=[3],['XX'],[0],[1],[4],['3']
type(my_list[0])
<class 'list'>
答案 0 :(得分:3)
之所以得到list
,是因为您检查了0
中索引为tuple
的元素list
>>> my_list=[3],['XX'],[0],[1],[4],['3'] # my_list is a tuple now :)
>>> [y.__class__ for x in my_list for y in x]
[<type 'int'>, <type 'str'>, <type 'int'>, <type 'int'>, <type 'int'>, <type 'str'>]
>>> [y.__class__.__name__ for x in my_list for y in x]
['int', 'str', 'int', 'int', 'int', 'str']
答案 1 :(得分:1)
type
返回列表,因为您拥有的是列表的元组
my_list=[3],['XX'],[0],[1],[4],['3']
等同于
my_list=([3],['XX'],[0],[1],[4],['3'])
您要将其定义为
my_list = [3,'xx',0,1,4,'3']
答案 2 :(得分:0)
您的my_list
变量是一个列表列表。
my_list=[3,'XX', 0, 1, 4, '3']