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

标签 python

我想展平可能包含其他列表的列表而不将字符串分开。例如:

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__') and not isinstance(x, str):
            for y in flatten(x):
                yield y
        else:
            yield x

Python 2.x 的旧版本:

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

(在 Python 2.x 中,字符串很方便地实际上没有 __iter__ 属性,这与 Python 中几乎所有其他可迭代对象不同。但是请注意,它们在 Python 3 中具有,所以上面代码仅适用于 Python 2.x。)

关于python - 如何在不拆分字符串的情况下展平列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5286541/

相关文章:

python - while 循环 "continue"在尝试内不起作用,除了,最后

Python 元组重组

python - 将多个时间序列数据组合到一个 2d numpy 数组

python - 在 python 中创建词汇表

python - 使用 pyInstaller 2.0 创建具有特定参数的 python 脚本的可执行文件

python - 单元格编辑期间 QTableWidgetItem 中的居中文本

python - 用填充堆叠 numpy 数组

python - Google Cloud Endpoints 的自定义身份验证(而不是 OAuth2)

python - 将 CSV 表转换为 Redis 数据结构

python - TensorFlow 中的 GRUCell : TypeError got multiple values for keyword argument 'num_units'