Skip to content Skip to sidebar Skip to footer

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:

defngram(inp='', mn=2, mx=60):
    return [inp[i:j] 
            for i inrange(0, len(inp) + 1 - mn)
            for j inrange(i + mn, min(i + mx + 1, len(inp) + 1))]

In general, whenever you have a for loop of this form:

result = []
forsub_1in collection:
    forsub_2in sub_1:
        …
            forsub_ninsub_(n - 1):
                result.append(element)

You can construct an equivalent list comprehension of the following form:

[element forsub_1in collection forsub_2in sub_1 … forsub_ninsub_(n - 1)]

Solution 2:

What's wrong with:

defngram(inp='', mn=2, mx=60): 
    return [
        inp[i:j]
        for i inrange(0, len(inp) + 1 - mn)
        for j inrange(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"