Converting Nested For Loops To Flattened List Comprehension When Outer Variable Is Used In Inner Scope
I have a pair of nested loops where the operation inside the inner loop depend on both the loop elements. def ngram(inp='', mn=2, mx=60): ''' EG inp='the' => ['th', 'the
Solution 1:
You can do this:
def ngram(inp='', mn=2, mx=60):
return [inp[i:j]
for i in range(0, len(inp) + 1 - mn)
for j in range(i + mn, min(i + mx + 1, len(inp) + 1))]
In general, whenever you have a for loop of this form:
result = []
for sub_1 in collection:
for sub_2 in sub_1:
…
for sub_n in sub_(n - 1):
result.append(element)
You can construct an equivalent list
comprehension of the following form:
[element for sub_1 in collection for sub_2 in sub_1 … for sub_n in sub_(n - 1)]
Solution 2:
What's wrong with:
def ngram(inp='', mn=2, mx=60):
return [
inp[i:j]
for i in range(0, len(inp) + 1 - mn)
for j in range(i+mn, min(i + mx + 1, len(inp) + 1))
]
Post a Comment for "Converting Nested For Loops To Flattened List Comprehension When Outer Variable Is Used In Inner Scope"