2017-08-03 152 views
-1

我抬头其他线程对这个错误“类型错误:‘类型’对象不是可迭代”,但我不是很理解什么是错的Python的类型错误:“类型”对象不是可迭代

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) 
+0

'对于类型(a)中的价值:'你在这里做什么? –

+0

@ WillemVanOnsem-根据元素的数据类型,编写一个程序,该列表根据列表中的每个元素输出一个消息,并在该列表中输出一条消息 。 您的程序输入将始终是一个列表。对于列表中的每个项目, 测试其数据类型。如果该项目是一个字符串,将其连接到一个新的字符串。 如果它是一个数字,将其添加到运行总和。在程序结束时,打印 字符串,数字和分析列表包含的内容。如果它仅包含 一种类型,则打印该类型,否则打印“混合” –

回答

0

如果你查询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)

而且你应该printlistType的结果,因为它不return什么,并修复该程序的缩进。我希望现在是正确的。

相关问题