部分列表Python中的拼合 [英] Partial list Flattening in Python

查看:89
本文介绍了部分列表Python中的拼合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题,我缺乏一些Python经验. 假设有一个列表:

I have a small problem where I lack quite some Python experience. Assuming a list:

list=[[40, 20, 45, 40], [[20, 10, 10, 30, 45, 20], [30, 20, 20, 30]]]

我想做我称之为部分展平"的事情,因为预期的输出是:

I want to do something I call 'partial flattening' because the expected output is:

[[40, 20, 45, 40], [20, 10, 10, 30, 45, 20], [30, 20, 20, 30]]

list的长度为2之前发出通知,而预期输出的长度为3.问题是我事先不知道list中的哪个元素嵌套更深一层.

Notice before the lentgh of list was 2 while the expected output has length of 3. The problem is that I don't know in advance which element from list is nested one layer deeper.

此答案以及其他许多问题并没有多大帮助,因为扁平化已远远超过了.在问题之后的输出是:

This answer and many others didn't help much, because the flattening goes to far. Following the question the output is:

list=[40, 20, 45, 40, [20, 10, 10, 30, 45, 20], [30, 20, 20, 30]]

(请注意列表中前4个元素的缺失括号.

(notice the missing brackets for the first 4 elements from the list.

推荐答案

您可以创建一个递归函数,测试all内部元素是否为列表.如果是这样,则递归地应用该算法,否则产生列表本身.

You can create a recursive function, testing whether all the inner elements are lists. If so, recursively apply the algorithm, otherwise yield the list itself.

def inner_lists(lst):
    if all(isinstance(x, list) for x in lst):
        for inner in lst:
            for x in inner_lists(inner):
                yield x
    else:
        yield lst

>>> lst = [[40, 20, 45, 40], [[20, 10, 10, 30, 45, 20], [30, 20, 20, 30]]]
>>> list(inner_lists(lst))
[[40, 20, 45, 40], [20, 10, 10, 30, 45, 20], [30, 20, 20, 30]]

或使用yield from(Python 3.3和更高版本):

Or using yield from (Python 3.3 and later):

def inner_lists(lst):
    if all(isinstance(x, list) for x in lst):
        yield from (x for inner in lst for x in inner_lists(inner))
    else:
        yield lst

或者没有发电机:

def inner_lists(lst):
    if all(isinstance(x, list) for x in lst):
        return [x for inner in lst for x in inner_lists(inner)]
    else:
        return [lst]

这篇关于部分列表Python中的拼合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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