How to print types within a list

前端 未结 6 1670
自闭症患者
自闭症患者 2021-01-03 02:01

So I was given a list and I must print the type of each item in the list. I can clearly see that there are strings and integers but I need it to print out in Python. We just

相关标签:
6条回答
  • 2021-01-03 02:33
     a=[12,"string"]
     for i in a: #sets the value of a to be any item in list (a)
          print(type(a), end="   ")
    

    OUTPUT:

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

    In the python code above type() function is used to determine the data type of variable (i). And end() is used to replace the end of the output with the value inside its' brackets () instead of a new line as you must have observed in the above output that between the 2 outputs "____ " (space) was placed without a new line.

    0 讨论(0)
  • 2021-01-03 02:34

    Here is how I would do it using type().

    myList = [1,1.0,"moo"]  #init the array
    for i in myList: 
        print(type(i)) #loop and print the type
    
    0 讨论(0)
  • 2021-01-03 02:38

    use the type built in function of python.

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

    output:

    <type 'str'>
    <type 'int'>
    <type 'int'>
    <type 'str'>
    
    0 讨论(0)
  • 2021-01-03 02:47
    foo = [1, 0.2, "bar"]
    for i in foo:
        print(type(i))
    

    Should print out the type of each item

    0 讨论(0)
  • 2021-01-03 02:51
    ls = [type(item) for item in list_of_items]
    print(ls)
    
    0 讨论(0)
  • 2021-01-03 02:57

    Essentially, the type function takes an object and returns the type of it. Try the below code:

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

    Output:

    <type 'int'>
    <type 'int'>
    <type 'int'>
    <type 'str'>
    <type 'NoneType'>
    
    0 讨论(0)
提交回复
热议问题