2012-11-10 64 views
-1

我開始了一個suduko項目,我需要將列表「board」中的所有0替換爲「」。 爲什麼它不起作用?替換列表中的字符

我得到這個錯誤:

AttributeError: 'list' object has no attribute 'replace' 

我的代碼:

board = [[3,7,0,0,5,0,0,0,0], 
     [0,6,0,0,3,0,2,0,0], 
     [0,2,9,4,0,0,0,7,8], 
     [0,0,4,1,7,0,0,8,0], 
     [0,0,6,3,0,5,9,0,0], 
     [0,5,0,0,8,4,1,0,0], 
     [7,1,0,0,0,8,5,6,0], 
     [0,0,5,0,1,0,0,2,0], 
     [0,0,0,0,9,0,0,1,3]] 

def print_board(board): 
    pass 
    a=-1 
    board=board.replace(0, " ") 
    for i in board: 
     a+=1 

     if a%3==0: 

      print 25*"*"+"" 
      print "*",i[0],i[1],i[2],"*",i[3],i[4],i[5],"*",i[6],i[7],i[8],"*" 

     else: 
      print "*",i[0],i[1],i[2],"*",i[3],i[4],i[5],"*",i[6],i[7],i[8],"*" 
    print 25*"*"+"" 
+3

即使錯誤說得很清楚:'list沒有名爲replace的屬性,'replace()'用於字符串而不是列表。 –

+0

'replace'是一個字符串方法 -​​ 所以列表沒有那個方法。你可能需要一個列表理解或地圖。 –

+0

哎呀.. 還有另一種方法來取代它嗎? – user1562379

回答

2

嘗試這樣的事情,使用列表理解:

In [10]: board 
Out[10]: 
[[3, 7, 0, 0, 5, 0, 0, 0, 0], 
[0, 6, 0, 0, 3, 0, 2, 0, 0], 
[0, 2, 9, 4, 0, 0, 0, 7, 8], 
[0, 0, 4, 1, 7, 0, 0, 8, 0], 
[0, 0, 6, 3, 0, 5, 9, 0, 0], 
[0, 5, 0, 0, 8, 4, 1, 0, 0], 
[7, 1, 0, 0, 0, 8, 5, 6, 0], 
[0, 0, 5, 0, 1, 0, 0, 2, 0], 
[0, 0, 0, 0, 9, 0, 0, 1, 3]] 

In [11]: board=[[x if x!=0 else " " for x in i] for i in board] 

In [12]: board 
Out[12]: 
[[3, 7, ' ', ' ', 5, ' ', ' ', ' ', ' '], 
[' ', 6, ' ', ' ', 3, ' ', 2, ' ', ' '], 
[' ', 2, 9, 4, ' ', ' ', ' ', 7, 8], 
[' ', ' ', 4, 1, 7, ' ', ' ', 8, ' '], 
[' ', ' ', 6, 3, ' ', 5, 9, ' ', ' '], 
[' ', 5, ' ', ' ', 8, 4, 1, ' ', ' '], 
[7, 1, ' ', ' ', ' ', 8, 5, 6, ' '], 
[' ', ' ', 5, ' ', 1, ' ', ' ', 2, ' '], 
[' ', ' ', ' ', ' ', 9, ' ', ' ', 1, 3]] 
+0

我可以做'board = [[「」如果0爲x在線]爲線路板]'? – user1562379

+0

@ user1562379不,你不能,這是錯誤的。我的回答有什麼問題? –

+0

沒有錯,但它似乎毫無用處告訴python保持原樣。所以我想我可以告訴他只是我想改變 – user1562379

1

您可以使用列表理解:

board = [[3,7,0,0,5,0,0,0,0], 
     [0,6,0,0,3,0,2,0,0], 
     [0,2,9,4,0,0,0,7,8], 
     [0,0,4,1,7,0,0,8,0], 
     [0,0,6,3,0,5,9,0,0], 
     [0,5,0,0,8,4,1,0,0], 
     [7,1,0,0,0,8,5,6,0], 
     [0,0,5,0,1,0,0,2,0], 
     [0,0,0,0,9,0,0,1,3]] 

board = [[x if x else ' ' for x in line] for line in board] 

board = [[3,7,' ',' ',5,' ',' ',' ',' '], 
     [' ',6,' ',' ',3,' ',2,' ',' '], 
     [' ',2,9,4,' ',' ',' ',7,8], 
     [' ',' ',4,1,7,' ',' ',8,' '], 
     [' ',' ',6,3,' ',5,9,' ',' '], 
     [' ',5,' ',' ',8,4,1,' ',' '], 
     [7,1,' ',' ',' ',8,5,6,' '], 
     [' ',' ',5,' ',1,' ',' ',2,' '], 
     [' ',' ',' ',' ',9,' ',' ',1,3]] 

或者您可以使用map()map(lambda line: [x if x else ' ' for x in line], board)

+0

只能使用更改項嗎? – user1562379