如何在不拆分字符串的情况下展平列表?

Cev*_*Cev 18 python

我想压缩可能包含其他列表的列表,而不会破坏字符串.例如:

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

而且我想

['cat', 'dog', 'bird']
Run Code Online (Sandbox Code Playgroud)

Amb*_*ber 23

def flatten(foo):
    for x in foo:
        if hasattr(x, '__iter__'):
            for y in flatten(x):
                yield y
        else:
            yield x
Run Code Online (Sandbox Code Playgroud)

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

Python 3.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
Run Code Online (Sandbox Code Playgroud)


Geo*_*edy 5

对orip的答案进行了轻微修改,避免了创建中间列表:

import itertools
items = ['cat',['dog','bird']]
itertools.chain.from_iterable(itertools.repeat(x,1) if isinstance(x,str) else x for x in items)
Run Code Online (Sandbox Code Playgroud)