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
However, the question also raises the possibility of alternative approaches using generator functions.
Generator-based functions can simplify the flattening process and potentially improve performance. Here are examples for Python 2 and 3:
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
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
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!