如何转换下面的嵌套列表?
d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]
-> [['a','b','c'], ['d','e','f']]
我发现了一个类似的问题。但它有点不同。 join list of lists in python [duplicate]
我的不聪明
new = []
for elm in d:
tmp = []
for e in elm:
for ee in e:
tmp.append(ee)
new.append(tmp)
print(new)
[['a', 'b', 'c'], ['d', 'e', 'f']]
答案 0 :(得分:2)
有很多方法可以做到这一点,但一种方法是使用链
from itertools import chain
[list(chain(*x)) for x in d]
结果:
[['a', 'b', 'c'], ['d', 'e', 'f']]
答案 1 :(得分:1)
sum(ls, [])
压扁列表有问题,但对于简短列表来说,它太简洁了,没有提及
d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]
[sum(ls, []) for ls in d]
Out[14]: [['a', 'b', 'c'], ['d', 'e', 'f']]
答案 2 :(得分:0)
这是一个简单的问题解决方案
new_d = []
for inner in d:
new_d.append([item for x in inner for item in x])