将列表列表/嵌套列表转换为列表列表而不进行嵌套 [英] Converting list of lists / nested lists to list of lists without nesting

查看:160
本文介绍了将列表列表/嵌套列表转换为列表列表而不进行嵌套的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将列表转换为列表,并且在这些列表中,仅将列表转换为列表.例如:

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

我的代码:

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)

当前:

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

符合预期:

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

我当前的代码可用于查找预期的输出.但是,我必须使用太多的for循环及其太深的内容.有没有像一两行这样的更短方法呢?

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?

推荐答案

这里似乎已经解决了所有简短的方法,是对大多数这些过程中正在发生的事情的扩展解释.您几乎是unpacking嵌套列表,并且没有碰到空列表.

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

这篇关于将列表列表/嵌套列表转换为列表列表而不进行嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆