0

如何检查列表中所有元素的类型?

例如我有一个列表:

li = ["Hello", 12121, False]

如何制作一个遍历列表中每个元素并输出每个元素类型的程序

比如“Hell”就是一个字符串

12121 是一个整数

False 是一个布尔值。

4

1 回答 1

0

Check out Python's built-in isintance method, and also the type method. To find out for the whole list, you could simply iterate through the list and output the resultant of the type method.

For example:

for item in list:
    print type(item)

Or if you are expecting certain types:

for item in list:
    if isinstance(item,basestring):
        print "I am a type of string!"
    if isinstance(item,(str,unicode)):
        print "I am a str or unicode!"
    if isinstance(item,int):
        print "I am a type of int!"
    if isinstance(item,(int,float)):
        print "I am an int or a float!"
    if isinstance(item,bool):
        print "I am a boolean!"
    if isinstance(True,bool):
        print "I am a boolean!"
    if isinstance(True,int):
        print "I am an int!"  # because booleans inherit from integers ;)

The isinstance method is usually better because it checks against inherited classes. See this post for a detailed discussion.

于 2013-10-31T18:06:50.280 回答