我有以下输入数据。 我可以为除最后一个字段之外的所有其他字段创建嵌套列表。最后一个字符串字段还可以在单词之间包含空格(例如: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]
关于python - 在 python 中为字符串字段创建嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58822523/