Flattening Results of List Comprehension
In Python, using a list comprehension to apply a function to each element of a list can result in nested lists. For instance, considering a list A and a function f that transforms each element of A into a list, the list comprehension [f(a) for a in A] produces a list of lists.
To obtain a flattened list, not unlike functional programming's 'flatmap' or .NET's 'SelectMany' operators, nesting can be introduced into the list comprehension:
<code class="python">[filename for path in dirs for filename in os.listdir(path)]</code>
This is functionally equivalent to the following code that uses multiple nested loops:
<code class="python">filenames = [] for path in dirs: for filename in os.listdir(path): filenames.append(filename)</code>
Adopting this approach ensures that a flat list is produced, where elements are obtained by first iterating over the outer list dirs and then the inner list returned by the function f applied to each element in dirs.
The above is the detailed content of How to Flatten Nested Lists from List Comprehensions in Python?. For more information, please follow other related articles on the PHP Chinese website!