Independent Iterators in List Comprehension
In Python, list comprehensions allow multiple iteration loops. Consider the following example:
<code class="python">[(x, y) for x in a for y in b]</code>
where a and b are sequences. This comprehension creates pairs of elements from the Cartesian product of a and b.
Can Iterators Be Dependent?
Can one iterator in a list comprehension refer to another? The answer is yes, and the following code demonstrates it:
<code class="python">[x for x in a for a in b]</code>
In this comprehension, the outer loop iterator a becomes the iterator for the inner loop. This effectively flattens a nested list.
Example
If we have a nested list a:
<code class="python">a = [[1, 2], [3, 4]]</code>
The following list comprehension would flatten it into a single list:
<code class="python">[x for x in a for a in b]</code>
Result:
[1, 2, 3, 4]
Alternative Solution Using Generators
In the provided Python code, the text is stored as sentences, and the task is to extract a single list of words. Here's how you can achieve this using a generator:
<code class="python">text = (("Hi", "Steve!"), ("What's", "up?")) gen = (word for sentence in text for word in sentence)</code>
The gen variable now yields the flattened list of words:
<code class="python">for word in gen: print(word)</code>
Output:
Hi Steve! What's up?
The above is the detailed content of Can List Comprehensions Have Dependent Iterators?. For more information, please follow other related articles on the PHP Chinese website!