Python TypeError:'type'对象不可迭代

时间:2017-08-03 18:11:25

标签: python-2.7

我在这个错误上查找了其他线程“TypeError:'type'对象不可迭代”,但我不太清楚错误是什么

a = ["Hey","Oh",32,12,"No",41]
b = [23,65,2,7,21,29]
c = ["My","Friends","At","Coding","Dojo"]

def listType(arg):
    new_string = ""
    numSum = 0

for value in type(a):
    if isinstance(value,int) or isinstance(value,float):
        numSum += value
    elif isinstance(value,str):
        new_string += value  
    if new_string and numSum:
        print "String:", new_string
        print "Sum:", numSum
        print "This list is of mixed type"
    elif new_string:
        print "String:", new_string
        print "This list is of string type"
    else:
        print "Sum:", numSum
        print "This list is of integer type" 

print listType(a)

1 个答案:

答案 0 :(得分:1)

如果您查询type(a),则会获得list。您可能希望对相应类型执行元素的映射,因此请使用map

def listType(a):
    new_string = ""
    numSum = 0
    for value in map(type,a):
        if isinstance(value,int) or isinstance(value,float):
            numSum += value
        elif isinstance(value,str):
            new_string += value  

    if new_string and numSum:
        print "String:", new_string
        print "Sum:", numSum
        print "This list is of mixed type"
    elif new_string:
        print "String:", new_string
        print "This list is of string type"
    else:
        print "Sum:", numSum
        print "This list is of integer type"

listType(a)

此外, print listType的结果,因为它不会return任何内容,并修复程序的缩进。我希望现在是正确的。