【问题标题】:How to print types within a list如何打印列表中的类型
【发布时间】:2016-05-03 20:49:55
【问题描述】:

所以我得到了一个列表,我必须打印列表中每个项目的类型。我可以清楚地看到有字符串和整数,但我需要它在 Python 中打印出来。我们刚刚学习了 for 循环,所以我觉得这就是他们正在寻找的东西,但我无法将其打印出来。

【问题讨论】:

  • 查看任何python教程,你应该可以自己做
  • 所以这是列表:several_things = ["hello", 2, 4, 6.0, 7.5, 234352354, "the end", "", 99] 我用 for aseveral_thing in几个东西: 然后下一行我使用 print type aseveral_thing 他们在我们的讲座中做了类似的事情,但我很新,不确定它是否仍然有效
  • 这能回答你的问题吗? How to determine a Python variable's type?

标签: python list types


【解决方案1】:
 a=[12,"string"]
 for i in a: #sets the value of a to be any item in list (a)
      print(type(a), end="   ")

输出:

>>>  <type 'int'>    <type 'str'>

在上面的python代码中type()函数用于判断变量(i)的数据类型。并且 end() 用于将输出的结尾替换为其括号 () 内的值,而不是一个新行,正如您在上面的输出中必须观察到的那样,在 2 个输出之间放置“____”(空格)没有换行。

【讨论】:

    【解决方案2】:
    ls = [type(item) for item in list_of_items]
    print(ls)
    

    【讨论】:

      【解决方案3】:
      foo = [1, 0.2, "bar"]
      for i in foo:
          print(type(i))
      

      应该打印出每个项目的类型

      【讨论】:

        【解决方案4】:

        本质上,type 函数接受一个对象并返回它的类型。试试下面的代码:

        for item in [1,2,3, 'string', None]:
            print type(item)
        

        输出:

        <type 'int'>
        <type 'int'>
        <type 'int'>
        <type 'str'>
        <type 'NoneType'>
        

        【讨论】:

          【解决方案5】:

          使用python内置的type函数。

          lst = ['string', 1, 2, 'another string']
          for element in lst:
             print type(element)
          

          输出:

          <type 'str'>
          <type 'int'>
          <type 'int'>
          <type 'str'>
          

          【讨论】:

            【解决方案6】:

            这是我使用type() 的方法。

            myList = [1,1.0,"moo"]  #init the array
            for i in myList: 
                print(type(i)) #loop and print the type
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2020-02-11
              • 1970-01-01
              • 2022-01-14
              • 2022-01-11
              • 1970-01-01
              • 1970-01-01
              • 2023-03-26
              • 1970-01-01
              相关资源
              最近更新 更多