2011-12-30 43 views
2

當我運行我的程序時出現此錯誤,我不知道爲什麼。該錯誤發生在,說:「如果1沒有在C:」行TypeError:類型'int'的參數不可迭代

代碼:

matrix = [ 
    [0, 0, 0, 5, 0, 0, 0, 0, 6], 
    [8, 0, 0, 0, 4, 7, 5, 0, 3], 
    [0, 5, 0, 0, 0, 3, 0, 0, 0], 
    [0, 7, 0, 8, 0, 0, 0, 0, 9], 
    [0, 0, 0, 0, 1, 0, 0, 0, 0], 
    [9, 0, 0, 0, 0, 4, 0, 2, 0], 
    [0, 0, 0, 9, 0, 0, 0, 1, 0], 
    [7, 0, 8, 3, 2, 0, 0, 0, 5], 
    [3, 0, 0, 0, 0, 8, 0, 0, 0], 
    ] 
a = 1 
while a: 
    try: 
     for c, row in enumerate(matrix): 
      if 0 in row: 
       print("Found 0 on row,", c, "index", row.index(0)) 
       if 1 not in c: 
        print ("t") 
    except ValueError: 
     break 

我想知道的是如何從發生修正這個錯誤的還有節目正確運行。

在此先感謝!

回答

8

此處c是索引而不是您正在搜索的列表。既然你不能遍歷一個整數,你會得到這個錯誤。



>>> myList = ['a','b','c','d'] 
>>> for c,element in enumerate(myList): 
...  print c,element 
... 
0 a 
1 b 
2 c 
3 d 

您正試圖檢查1c,這沒有任何意義

0

c是行數,所以它是一個int。所以數字不能是in其他數字。

+0

我該如何在沒有錯誤的情況下執行此操作? – chingchong 2011-12-30 01:19:45

+0

你想做什麼? (什麼時候應該打印't'?) – BenH 2011-12-30 01:24:26

+0

如果一行中有0並且行中沒有1,它應該打印「t」。 – chingchong 2011-12-30 01:25:47

0

我認爲你想if 1 != c: - 測試c是否沒有值1

+0

雖然會工作嗎?它會檢查0所在的行嗎? – chingchong 2011-12-30 01:24:16

0

你正在嘗試迭代'c',它只是一個整數,持有你的行號。

It should print "t" if there is a 0 in a row

然後,只需更換與該行的C所以它說:

if 1 not in row: 
2

基礎上OP的評論It should print "t" if there is a 0 in a row and there is not a 1 in the row.

變化if 1 not in cif 1 not in row

for c, row in enumerate(matrix): 
    if 0 in row: 
     print("Found 0 on row,", c, "index", row.index(0)) 
     if 1 not in row: #change here 
      print ("t") 

進一步澄清:可變霍爾row ds單行本身,即[0, 5, 0, 0, 0, 3, 0, 0, 0]c變量保持的索引,其中是行。即,如果row在矩陣中保存第3行,則爲c = 2。請記住,c是從零開始的,即第一行位於索引0,第二行位於索引1等。

+0

感謝這真的接近我所期待的! – chingchong 2011-12-30 01:39:12

+0

我仍然困惑的事情是,當他們是多行,其中0。它會爲所有這些行執行嗎? – chingchong 2011-12-30 01:40:14

+0

@chingchong是的,它會打印「在行上找到0 ...」,每行上有一個0。這是因爲我們通過'for c,inumeume(matrix)'中的行循環矩陣中的行 – 2011-12-30 03:07:28

相關問題