提问者:小点点

将字符串列表的列表转换为列表列表的列表[重复]


你好,我有一个字符串列表,看起来像这样

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

但这不起作用


共2个答案

匿名用户

给你

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']]]