Све*_*вов 1 python string list
我有当前的字符串:
output = "S.##......\n#.##..###.\n#.###.###.\n#.....###.\n###.#####S"
Run Code Online (Sandbox Code Playgroud)
我想将其转换为以下列表:
coordinates = [['S', '.', '#', '#', '.', '.', '.', '.', '.', '.'],
['#', '.', '#', '#', '.', '.', '#', '#', '#', '.'],
['#', '.', '#', '#', '#', '.', '#', '#', '#', '.'],
['#', '.', '.', '.', '.', '.', '#', '#', '#', '.'],
['#', '#', '#', '.', '#', '#', '#', '#', '#', 'S']]
Run Code Online (Sandbox Code Playgroud)
基本上每当我得到一个"\n"字符时,我希望它之前的序列像上面那样被拆分并放在一个单独的列表项中.我尝试了以下方法:
coordinates = []
temp = []
for item in output:
if item != "\n":
temp += item
else:
coordinates += temp
Run Code Online (Sandbox Code Playgroud)
但它不起作用,也不起作用
.append()
Run Code Online (Sandbox Code Playgroud)
在换行符上拆分str.splitlines()(以避免产生空的最后一行),然后调用list()每个结果字符串.您可以使用列表推导在一个表达式中执行此操作:
[list(line) for line in output.splitlines()]
Run Code Online (Sandbox Code Playgroud)
调用list()字符串会创建单个字符的列表对象:
>>> list('foo')
['f', 'o', 'o']
Run Code Online (Sandbox Code Playgroud)
演示:
>>> from pprint import pprint
>>> output = "S.##......\n#.##..###.\n#.###.###.\n#.....###.\n###.#####S"
>>> [list(line) for line in output.splitlines()]
[['S', '.', '#', '#', '.', '.', '.', '.', '.', '.'], ['#', '.', '#', '#', '.', '.', '#', '#', '#', '.'], ['#', '.', '#', '#', '#', '.', '#', '#', '#', '.'], ['#', '.', '.', '.', '.', '.', '#', '#', '#', '.'], ['#', '#', '#', '.', '#', '#', '#', '#', '#', 'S']]
>>> pprint(_)
[['S', '.', '#', '#', '.', '.', '.', '.', '.', '.'],
['#', '.', '#', '#', '.', '.', '#', '#', '#', '.'],
['#', '.', '#', '#', '#', '.', '#', '#', '#', '.'],
['#', '.', '.', '.', '.', '.', '#', '#', '#', '.'],
['#', '#', '#', '.', '#', '#', '#', '#', '#', 'S']]
Run Code Online (Sandbox Code Playgroud)
您的尝试失败,因为您从未重置temp; 你需要在每次到达时创建一个新的空列表\n,而coordinates.append()不是使用+=(与以下内容相同coordinates.extend():
coordinates = []
temp = []
for item in output:
if item != "\n":
temp += item
else:
coordinates.append(temp)
temp = []
if temp:
coordinates.append(temp)
Run Code Online (Sandbox Code Playgroud)
你需要最后两行不要错过最后一个'\n'字符后面的最后一行.
| 归档时间: |
|
| 查看次数: |
1160 次 |
| 最近记录: |