替换列表列表中的字符

时间:2012-11-10 18:30:56

标签: python

我启动了一个数独项目,我需要将列表“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*"*"+""

2 个答案:

答案 0 :(得分: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]]

答案 1 :(得分: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)