Home > Backend Development > Python Tutorial > How Can Irregularly Nested Lists Be Efficiently Flattened in Python Using Recursive and Generator-Based Approaches?

How Can Irregularly Nested Lists Be Efficiently Flattened in Python Using Recursive and Generator-Based Approaches?

DDD
Release: 2024-12-28 03:19:15
Original
286 people have browsed it

How Can Irregularly Nested Lists Be Efficiently Flattened in Python Using Recursive and Generator-Based Approaches?

Flatten an Irregularly Nested List of Lists

The task of flattening a nested list of lists can be challenging, especially when the nesting is irregular. The question presented investigates the efficacy of the following flattening algorithm:

def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result
Copy after login

However, the question also raises the possibility of alternative approaches using generator functions.

Generator-Based Flattening

Generator-based functions can simplify the flattening process and potentially improve performance. Here are examples for Python 2 and 3:

Python 2

Utilizing the Iterable ABC introduced in Python 2.6:

from collections import Iterable

def flatten(xs):
    for x in xs:
        if isinstance(x, Iterable) and not isinstance(x, basestring):
            for item in flatten(x):
                yield item
        else:
            yield x
Copy after login

Python 3

In Python 3, the basestring type is no longer present, and the tuple (str, bytes) can be used instead. Additionally, the yield from operator simplifies the iteration over generators:

from collections.abc import Iterable

def flatten(xs):
    for x in xs:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            yield from flatten(x)
        else:
            yield x
Copy after login

The generator-based approach has the advantage of being more concise and potentially more efficient, as it avoids intermediate lists and accumulates the results step by step.

The above is the detailed content of How Can Irregularly Nested Lists Be Efficiently Flattened in Python Using Recursive and Generator-Based Approaches?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template