为什么这个for循环不能将标记识别为int,float,string或boolean?

时间:2015-09-04 17:50:50

标签: python list loops

这是一段简短的代码,用于检查某个变量的数据类型,返回显示False,然后是FalseFalse,{{1} }。有人可以告诉我这段代码有什么问题,以及我如何更有效地完成这样的流程?

examples = [100, 1.45, "Bob", True]
types = [int, float, str, bool]

for x in range(0, 3):
    if type(examples[x]) == type(types[x]):
        print("True")
    else:
        print("False")

4 个答案:

答案 0 :(得分:3)

您必须将类型与列表中的单词进行比较,而不是类型。 另请注意,range排除了第二个参数,因此您需要更好地range(0,4)range(4)

for x in range(0, 4):
    if type(examples[x]) == (types[x]):
        print("True")
    else:
        print("False")

更好的方法是使用isinstance

  

如果object参数是classinfo参数的实例,或者是(直接,间接或虚拟)子类的实例,则返回true。

您可以将代码更改为

for x in range(0, 4):
    if isinstance(examples[x],types[x]):
        print("True")
    else:
        print("False")

isinstance返回一个布尔值时,您可以直接执行

for x in range(0, 4):
    print(isinstance(examples[x],types[x]))

答案 1 :(得分:1)

types的元素是类(类型),type为每个元素返回typeexamples中没有任何类型,因此type(examples[x]) == type将始终评估为False

这应该有效:

for x in range(4):
    if type(examples[x]) == types[x]: # <- remove type(...)
        print("True")
    else:
        print("False")

您也可以使用mapisinstance执行此操作:

In [3]: for x in map(isinstance, examples, types):
   ...:     print(x)
   ...:     
True
True
True
True

答案 2 :(得分:1)

您不想type(types[x])types已包含类型。如果您选择类型类型,则会获得type

只需if type(examples[x]) == types[x]

更好的方法是这样做:

for example, typ in zip(examples, types):
    if type(example) == typ:
        print("True")
    else:
        print("False")

这具有比较列表中所有类型的附加优势,而不仅仅是前3个。

为什么要这样做是另一个问题。

答案 3 :(得分:0)

修复:

for x in range(0, 3):
    if type(examples[x]) == types[x]: # you were type(instance of type) => type 
        print("True")
    else:
        print("False")

改善:

for x in range(0, 4): # did you miss the last element?
    print isinstance(examples[x],types[x]) # refer to link

link : learn about isinstance()