【问题标题】:How can I determine which elements in a list are integers and which are strings? [duplicate]如何确定列表中的哪些元素是整数,哪些是字符串? [复制]
【发布时间】:2019-08-27 10:44:34
【问题描述】:

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

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

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

【问题讨论】:

  • 您知道如何查看内部列表,对吧? type(my_list[0][0])。 (顺便说一下,my_listtuple,而不是 list。)

标签: python string list


【解决方案1】:

您的my_list 变量是一个列表列表。用

再试一次
my_list=[3,'XX', 0, 1, 4, '3']

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您得到了list,因为您检查了tuple 中索引0 处的元素,即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']
      

      【讨论】:

      • 谢谢!很好的解决方案!
      • 通常不应该直接使用dunder 属性:)。请改用type :)
      猜你喜欢
      • 2015-12-09
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多