-1

数独プロジェクトを開始しましたが、リスト「ボード」のすべての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*"*"+""
4

2 に答える 2

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]]
于 2012-11-10T18:35:55.000 に答える
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)

于 2012-11-10T18:37:54.140 に答える