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

Dha*_*ans 1 python

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

input  = ['a1 a2 a3 a4 Hello! welcome','b1 b2 b3 b4 how are you','c1 c2 c3 c4 you are welcome']
Run Code Online (Sandbox Code Playgroud)

电流输出

[['a1', 'a2', 'a3', 'a4', 'Hello!', 'welcome'],   
 ['b1', 'b2', 'b3', 'b4', 'how', 'are', 'you'],   
 ['c1', 'c2', 'c3', 'c4', 'you', 'are', 'welcome']] 
Run Code Online (Sandbox Code Playgroud)

预期输出:

[['a1', 'a2', 'a3', 'a4','Hello! welcome'],     
 ['b1', 'b2', 'b3', 'b4','how are you'],   
 ['c1', 'c2', 'c3', 'c4','you are welcome']]    
Run Code Online (Sandbox Code Playgroud)

下面的代码行产生如上的当前输出,但我需要转换代码以获得预期的结果。任何人都可以让我知道实现预期结果的方法。

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

for i in range(len(nested)):
    list1.append(nested[i][0].split())
Run Code Online (Sandbox Code Playgroud)

Grz*_*ski 5

您可以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)
Run Code Online (Sandbox Code Playgroud)

输出:

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

[Program finished]
Run Code Online (Sandbox Code Playgroud)

参考:https : //docs.python.org/2/library/re.html