Python中的联合嵌套列表
如何转换下面这样的嵌套列表Python中的联合嵌套列表,python,python-3.x,list,Python,Python 3.x,List,如何转换下面这样的嵌套列表 d = [[['a','b'], ['c']], [['d'], ['e', 'f']]] -> [['a','b','c'], ['d','e','f']] 我发现了一个类似的问题。但有点不同。 更新 我的不聪明 new = [] for elm in d: tmp = [] for e in elm: for ee in e: tmp.append(ee) new.append(tm
d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]
-> [['a','b','c'], ['d','e','f']]
我发现了一个类似的问题。但有点不同。
更新
我的不聪明
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']]
这是你问题的简单解决方案
new_d = []
for inner in d:
new_d.append([item for x in inner for item in x])
这是你问题的简单解决方案
new_d = []
for inner in d:
new_d.append([item for x in inner for item in x])
有很多方法可以做到这一点,但有一种方法是使用链
from itertools import chain
[list(chain(*x)) for x in d]
结果:
[['a', 'b', 'c'], ['d', 'e', 'f']]
有很多方法可以做到这一点,但有一种方法是使用链
from itertools import chain
[list(chain(*x)) for x in d]
结果:
[['a', 'b', 'c'], ['d', 'e', 'f']]
sum(ls,[])
将列表展平有问题,但对于短列表来说,它太简洁了,不值得一提
d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]
[sum(ls, []) for ls in d]
Out[14]: [['a', 'b', 'c'], ['d', 'e', 'f']]
sum(ls,[])
将列表展平有问题,但对于短列表来说,它太简洁了,不值得一提
d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]
[sum(ls, []) for ls in d]
Out[14]: [['a', 'b', 'c'], ['d', 'e', 'f']]
向我们展示您的尝试我添加了我的解决方案。向我们展示您的尝试我添加了我的解决方案。可能重复的
范围(len(…)
间接寻址似乎是不必要的。[list(chain(*x))用于d中的x]
就足够了。诚然,出于某种原因,我倾向于迭代索引而不是项目,但由于更简单,我更改了答案。范围(len(…)间接寻址似乎没有必要。[list(chain(*x))表示d中的x]
就足够了。确实,出于某种原因,我倾向于迭代索引而不是项目,但更改了答案,因为这更简单。这也很好!这也很好!