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

2024-05-18 21:05:12 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我有一个字符串列表,如下所示

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()

但这是行不通的


Tags: and字符串列表cosbeeduocoaans
2条回答

你可以做:

  1. 一般解决方案:

    x=[[j.split(" ") for j in i] for i in x]
    
  2. 对于上述特殊情况

    x=[[i[0].split(" "),i[1].split(" ")] for i in x]
    

输出:

[[['and', 'bee', 'cos', 'dup', 'ete'], ['ans', 'bew', 'coa', 'duo', 'etr']], [['snd', 'nee', 'vos', 'fup', 'rte'], ['s
ns', '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"]]
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)

同样的结果

相关问题 更多 >

    热门问题