首页 > 解决方案 > 三重嵌套列表综合python。可能吗?

问题描述

我正在练习嵌套列表理解,我遇到了一些我无法解决的问题,也无法在网上找到任何解决方案:<

nested_lista = [[2,1,2,3],[1,2,3,4],[4,4,[16,1,3]]]

使用循环很容易遍历这个嵌套列表的每一层

def nested_loops():
    for x in nested_lista:

        for y in x:
            print(y)

            if type(y) == list:

                for z in y:
                    print(z)

输出:

2
1
2
3
1
2
3
4
4
4
[16, 1, 3]
16
1
3

现在我试图通过嵌套列表理解来实现类似的输出,但无论我尝试什么,它都不起作用;/

这是我想出的:

[[[print(y) for y in z if type(z)==list]print(z) for z in x]for x in nested_lista]

或者至少我尝试遍历最后一层,但它也不起作用

[[[print(y) for y in z if type(z)==list] for z in x]for x in nested_lista]

有可能解决这个问题还是我应该放弃?

标签: listlist-comprehension

解决方案


2 周假期后头脑清醒,我花了 +-30 分钟才得到答案。

准备好更多的巢穴:

answer = [[[print(y) if type(y) is not list else print(x) for x in y] if type(y) == list else print(y) for y in z]for z in nested_lista]

较短的结果相同:

answer2 = [[[print(x)  for x in y] if type(y) == list else print(y) for y in z]for z in nested_lista]

输出:

2
1
2
3
1
2
3
4
4
4
16
1
3

不知道为什么我得到了“ - ”。


推荐阅读