2017-08-03 228 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什麼,並修復該程序的縮進。我希望現在是正確的。

相關問題