Converting list of lists / nested lists to list of lists without nesting

﹥>﹥吖頭↗ 提交于 2019-12-10 20:59:01

问题


I want to convert my list of lists and within these lists there are list into only list of lists. For example:

My code:

a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
aaa = len(a)
aa = [[] for i in range(aaa)]
for i, x in enumerate(a):
    if len(x) != 0:
        for xx in x:
            for xxx in xx:
                aa[i].append(xxx)
print(aa)

Currently:

a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]

to expected:

[[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]

My current code works in finding the expected output. However, i have to use too many for loop and its too deep. Is there a shorter way to do so like just in one or 2 lines?


回答1:


You can do it with list comprehension, just by checking to see whether the nested list is empty or not, and, if not, replacing the outer list with the inner list (by index).

data = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]

result = [d[0] if d else d for d in data]
print(result)

# OUTPUT
# [[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]



回答2:


I used itertools for this . for more info flatten list of list in python

import itertools
a=[[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
a = [list(itertools.chain(*li)) for li in a]
print(a)

Output

[[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]



回答3:


Try next with iter:

a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
print([next(iter(i),[]) for i in a])

Output:

[[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]



回答4:


All the short methods look to have been resolved here is a expanded explanation of what is happening in most these processes. Pretty much you are unpacking the nested list and not touching the empty lists.

a = [[], [], [['around_the_world']], [['around_the_globe']], [], [], [], []]
result = []

for i in a:
    if i == []:
        result.append(i)
    else:
        result.append(*i)

print(result)
# [[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]



回答5:


Since you want to flatten the inner sub-lists, you can use list comprehension within a list comprehension:

[[i for s in l for i in s] for l in a]

This returns:

[[], [], ['around_the_world'], ['around_the_globe'], [], [], [], []]


来源:https://stackoverflow.com/questions/52658767/converting-list-of-lists-nested-lists-to-list-of-lists-without-nesting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!