你好,我有一个字符串列表,看起来像这样
x = [["and bee cos dup ete", "ans bew coa duo etr"], ["snd nee vos fup rte", "sns new voa fuo rtr"]]
我希望从用空格分隔的列表列表中的字符串中列出另一个列表,即:
x = [[[and,bee,cos,dup,ete], [ans,bew,coa,duo,etr]], [[snd,nee,vos,fup,rte], [sns,new,voa,fuo,rtr]]]
我试过了
for i in x:
for y in i:
y.split()
但这不起作用
给你
x = [["and bee cos dup ete", "ans bew coa duo etr"], ["snd nee vos fup rte", "sns new voa fuo rtr"]]
y = []
for sub in x:
y.append([])
for subsub in sub:
y[-1].append(subsub.split(" "))
print(y)
输出:
[[['and', 'bee', 'cos', 'dup', 'ete'], ['ans', 'bew', 'coa', 'duo', 'etr']], [['snd', 'nee', 'vos', 'fup', 'rte'], ['sns', 'new', 'voa', 'fuo', 'rtr']]]
编辑您也可以这样做,只需一个for loop
:
x = [["and bee cos dup ete", "ans bew coa duo etr"], ["snd nee vos fup rte", "sns new voa fuo rtr"]]
y = []
for sub in x:
y.append([[splitted for splitted in subsub.split(" ")] for subsub in sub])
print(y)
结果相同
您可以执行:
>
一般解决方案:
x=[[j.split(“”)表示i中的j]表示x中的i]
对于上述特殊情况
x=[[i[0].split(“”),i[1].split(“”)]表示x]
中的i
输出:
[[['and', 'bee', 'cos', 'dup', 'ete'], ['ans', 'bew', 'coa', 'duo', 'etr']], [['snd', 'nee', 'vos', 'fup', 'rte'], ['s
ns', 'new', 'voa', 'fuo', 'rtr']]]