[Tutor] List comp question
Ricardo Aráoz
ricaraoz at gmail.com
Sat Nov 3 18:43:13 CET 2007
Eric Brunson wrote:
> Ricardo Aráoz wrote:
>> Kent Johnson wrote:
>>
>>> I am building a list like this:
>>>
>>> tree = []
>>> for top in tops:
>>> l2 = level2(top)
>>> if l2:
>>> tree.append((top, l2))
>>>
>>> I would really like to turn this into a list comprehension:
>>>
>>> tree = [ (top, level2(top)) for top in tops if level2(top) ]
>>>
>>> but the call to level2() is expensive enough that I don't want to repeat
>>> it. Is there any way to do this or am I stuck with the (IMO ugly) loop form?
>>>
>>>
>> Just playing around here, but would this work and be better????
>>
>> tree = [ pair for pair in [ (top, level2(top)) for top in tops ]
>> if pair[1] ]
>>
>>
>
> I came up with something very similar:
>
> tops = [1,2,3,4,5]
>
> def level2(n):
> m = n ** 2
> if m%2:
> return m
> else:
> return False
>
> tree = [ (x, y) for x, y in [ ( x, level2(x) ) for x in tops ] if y ]
> print tree
> [(1, 1), (3, 9), (5, 25)]
>
>
> But, now I would debate conciseness vs. readability and
> maintainability. Will someone understand what's going on if they have
> to read it? Will you remember what it does in six months when you're
> maintaining it?
>
> Still, an interesting academic exercise. :-)
>
> e.
>
It is perfectly understandable. Maybe the reason for doing it will not
be clear, you can always put a comment explaining you don't want to call
level2() twice.
More information about the Tutor
mailing list