如何展平列表以返回包含所有元素的新列表? [英] How to flatten a list to return a new list with all the elements?

查看:47
本文介绍了如何展平列表以返回包含所有元素的新列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个名为 flatten_list 的函数,该函数将一个可能嵌套的列表作为输入,并返回一个包含输入列表所有元素的非嵌套列表.

我的代码:

def flatten_list(alist):""">>>flatten_list([1,2,3])[1, 2, 3]>>>flatten_list([1, [2,3], [4, 5], 6])[1, 2, 3, 4, 5, 6]"""flat_list = []对于 alist 中的元素:flat_list += 元素返回 flat_list

此代码适用于带有字符串的列表,但不适用于整数值.如何更改代码以使其适用于两者?

谢谢

解决方案

通常,这会递归完成,例如:

def flatten(input_, output=None):如果输出为无:输出 = []如果 isinstance(input_, basestring):输出.附加(输入_)别的:对于 input_ 中的项目:尝试:展平(项目,输出)除了类型错误:output.append(item)返回输出

这将适用于可迭代容器的任意组合(例如 setlisttupledict(仅键))和内容(例如 intfloatstr),使用常见的 EAFP Python 风格.请注意字符串的特定异常,您可能不希望将其解包!

几个用法示例:

<预><代码>>>>扁平化([1, [2, [3, [4, 5], 6], 7], 8])[1, 2, 3, 4, 5, 6, 7, 8]>>>flatten([1, "foo", ["bar", 2], 3])[1, 'foo', 'bar', 2, 3]>>>展平([1, (2, 3), {4: 5}])[1, 2, 3, 4]>>>展平(你好")['你好']

将不可迭代对象作为直接参数会发生什么:

<预><代码>>>>压平(1)回溯(最近一次调用最后一次):文件<pyshell#3>",第 1 行,在 <module> 中压平(1)文件<pyshell#1>",第 4 行,扁平化对于 input_ 中的项目:类型错误:int"对象不可迭代

I am trying to write a function called flatten_list that takes as input a list which may be nested, and returns a non-nested list with all the elements of the input list.

My code:

def flatten_list(alist):
    """
    >>> flatten_list([1,2,3])
    [1, 2, 3]
    >>> flatten_list([1, [2,3], [4, 5], 6])
    [1, 2, 3, 4, 5, 6]
    """
    flat_list = []
    for element in alist:
        flat_list += element
    return flat_list

This code works for lists with strings, but not integer values. How can I change the code so that it works for both?

thanks

解决方案

Generally, this would be done recursively, for example:

def flatten(input_, output=None):
    if output is None:
        output = []
    if isinstance(input_, basestring):
        output.append(input_)
    else:
        for item in input_:
            try:
                flatten(item, output)
            except TypeError:
                output.append(item)
    return output

This will work with any combination of iterable containers (e.g. set, list, tuple, dict (keys only)) and contents (e.g. int, float, str), using the common EAFP Python style. Note the specific exception for strings, which you probably don't want to be unpacked!

A few examples of usage:

>>> flatten([1, [2, [3, [4, 5], 6], 7], 8])
[1, 2, 3, 4, 5, 6, 7, 8]
>>> flatten([1, "foo", ["bar", 2], 3])
[1, 'foo', 'bar', 2, 3]
>>> flatten([1, (2, 3), {4: 5}])
[1, 2, 3, 4]
>>> flatten("hello")
['hello']

And what happens with non-iterables as direct arguments:

>>> flatten(1)

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    flatten(1)
  File "<pyshell#1>", line 4, in flatten
    for item in input_:
TypeError: 'int' object is not iterable

这篇关于如何展平列表以返回包含所有元素的新列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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