python - 从给定的 txt 文件中获取 X 和 Y 尺寸

标签 python readfile dimensions maze

我在 Python 中将一个 txt 文件(迷宫)上传到我的代码中。
例子:

10 8

+-+-+-+-+-+-+-+-+-+-+
|*      |           |
+ +-+-+ +     +-+ + +
|   |         |X  | |
+-+ + +-+     +-+-+ +
|       |     |     |
+-+-+-+-+ + + +-+   +
|         | |   |   |
+ +-+-+ +-+ +-+ +   +
| |       | |   |   |
+ + +-+-+ + + +-+   +
| |   | | | |   |   |
+ +-+ + +-+ +-+ +   +
| |       | |   |   |
+ +-+-+-+-+ + +-+   +
|                   |
+-+-+-+-+-+-+-+-+-+-+
我愿意保存第一行——迷宫的尺寸。
我写的代码只有在每个维度上都有一个数字时才有效。无论每个维度中有多少个数字,我如何获得维度。
在上面的例子中,我想得到 10 和 8。
我的代码:
def loadMaze(file_name):
    readIt = open(file_name, 'r')
    readLines = readIt.readlines()
    x_dim = int(readLines[0][0])
    y_dim = int(readLines[0][2])
    mazeList = [list(i.strip()) for i in readLines[1:]]
    return x_dim, y_dim, mazeList

最佳答案

您永远不会关闭您打开的文件。如 docs 中所述:

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.


您的其余代码可以使用 str.stplit 简洁地完成。和 multiple assignment . (下划线分配给维度和迷宫之间的空行作为“忽略”它的一种方式,因为大概您不希望它出现在迷宫列表中。)
def load_maze(file_name):
    with open(file_name) as f:
        dims, _, *maze_lines = [line.rstrip() for line in f]
    x, y = [int(dim) for dim in dims.split()]
    maze = [list(line) for line in maze_lines]
    return x, y, maze
我个人认为返回可能很好xy作为一个元组在一起,像这样:
return (x, y), maze
但这取决于你。

关于python - 从给定的 txt 文件中获取 X 和 Y 尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67231316/

相关文章:

python - 如何使用具有自定义属性的 django-haystack 搜索面?

python - 我如何从 Python 脚本中知道 Python 可执行文件的位置?

C# 字典如何从文件中读取键=值

php - CKFinder 3(不适用于 CKEditor)如何在选择或上传图像时强制用户进入具有特定尺寸的图像编辑区域

algorithm - 根据地 block 总数确定子地 block 面积

r - R 中 3D 数组的方差

python - Pandas 'Freq' 标签中的有效值是什么?

python - 使用 WebStorm 安装 Python 插件

java.util.NoSuchElementException - 在 XSSFSheet 上读取

c++ - 如何在 C++ 中将结构写入文件并读取文件?