将文本转换为一系列列表

时间:2016-10-28 21:48:25

标签: python

为了好玩 - 并学习python( 3.5 ),我正在编写一个数独求解器。目前,我在代码中对网格进行了硬编码,因此我可以开发/测试它。

# initialise list. It generates a 9x9 grid full of zeroes
matrix = [[0 for y in range(9)] for x in range(9)]

# generate hard-coded board. 0 means the cell is empty
matrix[0] = [0, 0, 3, 0, 2, 0, 6, 0, 0]
matrix[1] = [9, 0, 0, 3, 0, 5, 0, 0, 1]
matrix[2] = [0, 0, 1, 8, 0, 6, 4, 0, 0]
matrix[3] = [0, 0, 8, 1, 0, 2, 9, 0, 0]
matrix[4] = [7, 0, 0, 0, 0, 0, 0, 0, 8]
matrix[5] = [0, 0, 6, 7, 0, 8, 2, 0, 0]
matrix[6] = [0, 0, 2, 6, 0, 9, 5, 0, 0]
matrix[7] = [8, 0, 0, 2, 0, 3, 0, 0, 9]
matrix[8] = [0, 0, 5, 0, 1, 0, 3, 0, 0]

...对应于此网格:

- - 3 | - 2 - | 6 - - 
9 - - | 3 - 5 | - - 1 
- - 1 | 8 - 6 | 4 - - 
---------------------
- - 8 | 1 - 2 | 9 - - 
7 - - | - - 4 | 1 - 8 
- - 6 | 7 - 8 | 2 - - 
---------------------
- - 2 | 6 - 9 | 5 - - 
8 - - | 2 - 3 | - - 9 
- - 5 | 4 1 - | 3 - -

现在我已经能够解决这个特定的板子了(YAY!:),我想改变它以测试代码是否适用于新的拼图。我没有一个一个地改变数字,而是可以输入类似的东西:

new_puzzle = "
200080300
060070084
030500209
000105408
000000000
402706000
301007040
720040060
004010003"

并以某种方式将其转换为如上所述的矩阵(例如:

matrix[0] = [2,0,0,0,8,0,3,0,0]
matrix[1] = [0,6,0,0,7,0,0,8,4]
# etc...

1 个答案:

答案 0 :(得分:2)

首先,如果您想使用多行字符串,则必须使用"""

new_puzzle = """
200080300
...
"""

然后,您可以使用列表推导将行转换为列表列表:

>>> [list(map(int, row)) for row in new_puzzle.strip().splitlines()]
[[2, 0, 0, 0, 8, 0, 3, 0, 0], [0, 6, 0, 0, 7, 0, 0, 8, 4], [0, 3, 0, 5, 0, 0, 2, 0, 9], [0, 0, 0, 1, 0, 5, 4, 0, 8], [0, 0, 0, 0, 0, 0, 0, 0, 0], [4, 0, 2, 7, 0, 6, 0, 0, 0], [3, 0, 1, 0, 0, 7, 0, 4, 0], [7, 2, 0, 0, 4, 0, 0, 6, 0], [0, 0, 4, 0, 1, 0, 0, 0, 3]]