简体   繁体   English

Python中的联合嵌套列表

[英]Joint nested list in Python

How to convert a nested list like below? 如何转换如下的嵌套列表?

d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]
-> [['a','b','c'], ['d','e','f']]

I found a similar question. 我发现了类似的问题。 But it's a little different. 但这有点不同。 join list of lists in python [duplicate] 在python中加入列表列表

Update 更新

Mine is not smart 我的不聪明

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

Lots of ways to do this, but one way is with chain 有很多方法可以做到这一点,但是一种方法是使用链

from itertools import chain
[list(chain(*x)) for x in d]

results in: 结果是:

[['a', 'b', 'c'], ['d', 'e', 'f']]

sum(ls, []) to flatten a list has issues, but for short lists its just too concise to not mention sum(ls, [])使列表变平是有问题的,但是对于简短列表,它太简洁了,不予提及

d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]

[sum(ls, []) for ls in d]

Out[14]: [['a', 'b', 'c'], ['d', 'e', 'f']]

This is a simple solution for your question 这是您问题的简单解决方案

new_d = []
for inner in d:
    new_d.append([item for x in inner for item in x])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM