Python:如何在列表中打印类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35028272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:53:38  来源:igfitidea点击:

Python: How to print types within a list

pythonlisttypes

提问by RPmich

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 learned for loopsso I feel like that is what they are looking for but I cannot get it to print out.

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

回答by intboolstring

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

这是我将如何使用type().

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

回答by wasp8898

use the typebuilt in function of python.

使用typepython的内置函数。

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

output:

输出:

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

回答by Rudrani Angira

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

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

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

Output:

输出:

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

回答by ZetaRift

foo = [1, 0.2, "bar"]
for i in foo:
    print(type(i))

Should print out the type of each item

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

回答by Ashish Kumar

ls = [type(item) for item in list_of_items]
print(ls)