Skip to main content
 首页 » 编程设计

Python 将字符串转换为字符串列表的列表

2025年05月04日11jyk

我有当前字符串:

output = "S.##......\n#.##..###.\n#.###.###.\n#.....###.\n###.#####S"     

我想把它转换成下面的列表:

coordinates = [['S', '.', '#', '#', '.', '.', '.', '.', '.', '.'], 
               ['#', '.', '#', '#', '.', '.', '#', '#', '#', '.'], 
               ['#', '.', '#', '#', '#', '.', '#', '#', '#', '.'], 
               ['#', '.', '.', '.', '.', '.', '#', '#', '#', '.'], 
               ['#', '#', '#', '.', '#', '#', '#', '#', '#', 'S']]     

基本上每次我得到一个“\n”字符时,我都希望它之前的序列像上面那样被拆分并放在一个单独的列表项中。 我尝试了以下方法:

    coordinates = [] 
    temp = [] 
    for item in output: 
        if item != "\n": 
            temp += item 
        else: 
            coordinates += temp 

但它不起作用,它也不适用

.append() 

请您参考如下方法:

用 str.splitlines() 在换行符上拆分(以避免产生空的最后一行),然后对每个结果字符串调用 list()。您可以使用 list comprehension 在一个表达式中完成所有这些操作:

[list(line) for line in output.splitlines()] 

在字符串上调用 list() 创建单个字符的列表对象:

>>> list('foo') 
['f', 'o', 'o'] 

演示:

>>> from pprint import pprint 
>>> output = "S.##......\n#.##..###.\n#.###.###.\n#.....###.\n###.#####S"     
>>> [list(line) for line in output.splitlines()] 
[['S', '.', '#', '#', '.', '.', '.', '.', '.', '.'], ['#', '.', '#', '#', '.', '.', '#', '#', '#', '.'], ['#', '.', '#', '#', '#', '.', '#', '#', '#', '.'], ['#', '.', '.', '.', '.', '.', '#', '#', '#', '.'], ['#', '#', '#', '.', '#', '#', '#', '#', '#', 'S']] 
>>> pprint(_) 
[['S', '.', '#', '#', '.', '.', '.', '.', '.', '.'], 
 ['#', '.', '#', '#', '.', '.', '#', '#', '#', '.'], 
 ['#', '.', '#', '#', '#', '.', '#', '#', '#', '.'], 
 ['#', '.', '.', '.', '.', '.', '#', '#', '#', '.'], 
 ['#', '#', '#', '.', '#', '#', '#', '#', '#', 'S']] 

您的尝试失败了,因为您从未重置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) 

您需要最后两行,以免错过最后一个 '\n' 字符后的最后一行。