Skip to main content
 首页 » 编程设计

python之在 python 中为字符串字段创建嵌套列表

2025年05月04日12oomusou

我有以下输入数据。 我可以为除最后一个字段之外的所有其他字段创建嵌套列表。最后一个字符串字段还可以在单​​词之间包含空格(例如:Hello!welcome)。

input  = ['a1 a2 a3 a4 Hello! welcome','b1 b2 b3 b4 how are you','c1 c2 c3 c4 you are welcome'] 

当前输出:

[['a1', 'a2', 'a3', 'a4', 'Hello!', 'welcome'],    
 ['b1', 'b2', 'b3', 'b4', 'how', 'are', 'you'],    
 ['c1', 'c2', 'c3', 'c4', 'you', 'are', 'welcome']]  

预期输出:

[['a1', 'a2', 'a3', 'a4','Hello! welcome'],      
 ['b1', 'b2', 'b3', 'b4','how are you'],    
 ['c1', 'c2', 'c3', 'c4','you are welcome']]     

下面的代码行产生了上面的当前输出,但我需要转换代码以获得预期的结果。谁能告诉我实现预期结果的方法。

for ix in range(len(input) ): 
    nested.append(input[ix:ix + 1]) 
 
for i in range(len(nested)): 
    list1.append(nested[i][0].split()) 

请您参考如下方法:

您可以为此目的使用re.split:

import re 
 
input  = ['a1 a2 a3 a4 Hello! welcome','b1 b2 b3 b4 how are you','c1 c2 c3 c4 you are welcome'] 
 
res=[re.split(" ", el, maxsplit=4) for el in input] 
 
print(res) 

输出:

[['a1', 'a2', 'a3', 'a4', 'Hello! welcome'], ['b1', 'b2', 'b3', 'b4', 'how are you'], ['c1', 'c2', 'c3', 'c4', 'you are welcome']] 
 
[Program finished] 

引用:https://docs.python.org/2/library/re.html