如何确定列表中的哪些元素是整数,哪些是字符串?

时间:2019-04-05 13:51:10

标签: python string list

在Python 3.6中,我需要确定列表中的哪些元素包含整数,浮点数或字符串。

当我使用“类型”函数时,它返回一个列表元素,但是该元素包含什么?字符串还是函数?

my_list=[3],['XX'],[0],[1],[4],['3']
type(my_list[0])
<class 'list'>

3 个答案:

答案 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']