替换并打印2d list python中的字符

时间:2018-03-18 21:57:45

标签: python arrays

我在python中有一个2d列表(数组),我试图用不同的字符打印到控制台。

阵列:

maze_a = [[1,1,1,1,1,1,1,0,1,1,1,1,1,1,1],
[1,0,0,0,0,0,1,0,1,0,0,0,0,0,1],
[1,0,1,1,1,0,1,0,1,1,1,1,1,0,1],
[1,0,1,0,1,0,1,0,0,0,0,0,1,0,1],
[1,0,1,0,1,0,1,1,1,1,1,0,1,0,1],
[1,0,1,0,0,0,0,0,0,0,0,0,1,0,1],
[1,1,1,0,1,1,1,1,1,1,1,1,1,0,1],
[1,0,0,0,0,0,1,0,0,0,0,0,0,0,1],
[1,0,1,1,1,0,1,0,1,1,1,1,1,1,1],
[1,0,1,0,1,0,1,0,0,0,0,0,0,0,1],
[1,0,1,0,1,0,1,1,1,1,1,1,1,0,1],
[1,0,0,0,1,0,0,0,1,0,0,0,1,0,1],
[1,1,1,1,1,0,1,0,1,0,1,0,1,0,1],
[1,0,0,0,1,0,1,0,1,0,1,0,1,0,1],
[1,0,1,1,1,0,1,1,1,0,1,0,1,0,1],
[1,0,0,0,0,0,0,0,0,0,1,0,0,0,1],
[1,1,1,1,1,1,1,1,1,0,1,1,1,1,1]]

代码:

    for row in maze_a:
        print(*row)

当前输出:

1 1 1 1 1 1 1 0 1 1 1 1 1 1 1
1 0 0 0 0 0 1 0 1 0 0 0 0 0 1
1 0 1 1 1 0 1 0 1 1 1 1 1 0 1
1 0 1 0 1 0 1 0 0 0 0 0 1 0 1
1 0 1 0 1 0 1 1 1 1 1 0 1 0 1
1 0 1 0 0 0 0 0 0 0 0 0 1 0 1
1 1 1 0 1 1 1 1 1 1 1 1 1 0 1
1 0 0 0 0 0 1 0 0 0 0 0 0 0 1
1 0 1 1 1 0 1 0 1 1 1 1 1 1 1
1 0 1 0 1 0 1 0 0 0 0 0 0 0 1
1 0 1 0 1 0 1 1 1 1 1 1 1 0 1
1 0 0 0 1 0 0 0 1 0 0 0 1 0 1
1 1 1 1 1 0 1 0 1 0 1 0 1 0 1
1 0 0 0 1 0 1 0 1 0 1 0 1 0 1
1 0 1 1 1 0 1 1 1 0 1 0 1 0 1
1 0 0 0 0 0 0 0 0 0 1 0 0 0 1
1 1 1 1 1 1 1 1 1 0 1 1 1 1 1

我正在尝试添加到我的代码中来更改字符。我想将0作为空格,将1作为* s。

我试过.replace(0,'')但我似乎无法让它发挥作用。

我知道这似乎很容易,但我找不到我生活的答案。也许我不能使用print(*行)或者我需要先转换为字符串(我试过并失败了)?

1 个答案:

答案 0 :(得分:1)

尝试这个,它使用矩阵中的值作为索引到另一个包含要打印的字符的列表。还有其他方法可以做到这一点,但这很容易理解。

chars = [' ', '*']
for row in maze_a:
    for item in row:
        print(chars[item], end=' ')
    print()

使用maze_a值的结果打印输出是

* * * * * * *   * * * * * * * 
*           *   *           * 
*   * * *   *   * * * * *   * 
*   *   *   *           *   * 
*   *   *   * * * * *   *   * 
*   *                   *   * 
* * *   * * * * * * * * *   * 
*           *               * 
*   * * *   *   * * * * * * * 
*   *   *   *               * 
*   *   *   * * * * * * *   * 
*       *       *       *   * 
* * * * *   *   *   *   *   * 
*       *   *   *   *   *   * 
*   * * *   * * *   *   *   * 
*                   *       * 
* * * * * * * * *   * * * * * 

在此解决方案中,每行末尾都印有一个不可见的空格,这对您来说可能无关紧要。还有一点工作可以阻止这个空间。