且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何展平列表以返回包含所有元素的新列表?

更新时间:2023-12-05 17:41:40

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

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