0

我有这个单行:

board = [[int(cell) for cell in row] for row in [line.split() for line in boardFile]]

它读取这样的文本文件:

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

并创建一个像这样的多维数组:

[[0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 1, 0, 0, 0, 0, 0],
 [0, 1, 0, 1, 0, 0, 0, 0, 0],
 [0, 0, 1, 1, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0]]

但是,它看起来很不整洁,有人可以改进它吗?

4

3 回答 3

4
board = [map(int, line.split()) for line in boardFile]

board = [list(map(int, line.split())) for line in boardFile]在 Python 3 中。

于 2013-09-27T20:05:45.933 回答
2

简单的方法是

[[int(cell) for cell in line.split()] for line in boardFile]
于 2013-09-27T20:21:48.373 回答
0

根据您如何定义具有多个相邻空格的行,这可能更容易:

import sys
r=csv.reader(boardFile, delimiter=' ')
board=list(r)
于 2013-09-27T20:00:23.217 回答