我正在加载此地图文件
3
15
8
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 0 0 0 0
0 7 3 4 4 5 8 3 4 5 9 0 0 0 2
0 12 0 0 0 0 0 0 0 0 13 0 0 0 12
0 12 0 0 0 0 0 0 0 0 13 0 0 0 12
使用此
lines = [line.strip("\n").split(" ") for line in open("/Resources/Maps/level1.map")]
吐出
['3']
['15']
['8']
['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', '0', '0', '0', '0']
['0', '7', '3', '4', '4', '5', '8', '3', '4', '5', '9', '0', '0', '0', '2']
['0', '12', '0', '0', '0', '0', '0', '0', '0', '0', '13', '0', '0', '0', '12']
['0', '12', '0', '0', '0', '0', '0', '0', '0', '0', '13', '0', '0', '0', '12']
这种当前格式正如我所希望的那样
前三行告诉我地图的数量,行数,列数
但不是我想要它的类型。
输出是一个包含字符串列表的列表,如何将其转换为带有整数的列表?
是否可以直接在我用于加载地图的行中执行此操作?
答案 0 :(得分:0)
您可以使用map
将列表中的所有元素转换为int。
<强>实施例强>
lines = [map(int, line.strip("\n").split(" ")) for line in open("/Resources/Maps/level1.map")]
答案 1 :(得分:0)
您可以添加其他list comprehension和slice结果,如:
lines = [[int(num) for num in line.split(" ")]
for line in open("file1")][3:]
[
[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, 0, 0, 0, 0],
[0, 7, 3, 4, 4, 5, 8, 3, 4, 5, 9, 0, 0, 0, 2],
[0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 12],
[0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 12]
]