Python:递归拉平列表 [英] Python : Recursively flatten a list

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

问题描述

可能重复:
用Python整理的(不规则的)列表列表

Possible Duplicate:
Flatten (an irregular) list of lists in Python

我有一个列表l = [2, 9, [1, 13], 8, 6],我需要对其进行递归展平以获取l = [2, 9, 1, 13, 8, 6].我找不到办法.

I have a list l = [2, 9, [1, 13], 8, 6] which I need to flatten recursively to get l = [2, 9, 1, 13, 8, 6]. I can't find a way to do so.

PS-撰写本文时,在相关问题" 列表中找不到与我的疑问相符的问题.所以,如果这是重复的话,那么请把我指向老问题,而不是惹恼我. :)

PS - As of writing this, I couldn't find any question matching my doubt in the Related Questions' lists. So if this is a duplicate, then kindly just point me to the old question instead of flaming me. :)

推荐答案

如果您想展平任意嵌套的可迭代对象,可以尝试使用以下功能:

If you want to flatten arbitrarily nested iterables, you could try this function:

def flatten(x):
    try:
        it = iter(x)
    except TypeError:
        yield x
    else:
        for i in it:
            for j in flatten(i):
                yield j

示例:

a = [2, 9, [1, 13], 8, 6]
list(flatten(a))
# [2, 9, 1, 13, 8, 6]

请注意,该函数还会将字符串拼合为单个字符.

Note that the function would also flatten out strings to single characters.

这篇关于Python:递归拉平列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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