Skip to main content
 首页 » 编程设计

python之为什么这个 for 循环不能将索引识别为 int、float、string 或 boolean

2025年05月04日2998°冷暖

这是一小段代码,用于检查某个变量的数据类型,返回值是True,然后是False,False ,错误。有人能告诉我这段代码有什么问题吗?我该如何更有效地执行此类流程?

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") 

请您参考如下方法:

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

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

更好的方法是使用 isinstance

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.

您可以将代码更改为,

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

因为isinstance返回的是 bool 值,所以可以直接做

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