如何在不拆分字符串的情况下展平列表? [英] How can I flatten lists without splitting strings?

查看:51
本文介绍了如何在不拆分字符串的情况下展平列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想扁平化可能包含其他列表的列表 不将字符串分开.例如:

I'd like to flatten lists that may contain other lists without breaking strings apart. For example:

In [39]: list( itertools.chain(*["cat", ["dog","bird"]]) )
Out[39]: ['c', 'a', 't', 'dog', 'bird']

我愿意

['cat', 'dog', 'bird']

推荐答案

def flatten(foo):
    for x in foo:
        if hasattr(x, '__iter__'):
            for y in flatten(x):
                yield y
        else:
            yield x

(字符串实际上没有 __iter__ 属性,这与 Python 中几乎所有其他可迭代对象不同.但请注意,这在 Python 3 中发生了变化,因此上述代码仅适用于 Python 2.x.)

(Strings conveniently do not actually have an __iter__ attribute, unlike pretty much every other iterable object in Python. Note however that this changes in Python 3, so the above code will only work in Python 2.x.)

def flatten(foo):
    for x in foo:
        if hasattr(x, '__iter__') and not isinstance(x, str):
            for y in flatten(x):
                yield y
        else:
            yield x

这篇关于如何在不拆分字符串的情况下展平列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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