[Tutor] list comprehension with else
pasokan at talentsprint.com
Sun Jan 18 14:41:10 CET 2015
On Sun, Jan 18, 2015 at 6:50 PM, Sydney Shall <s.shall at virginmedia.com>
> I am a beginner and I have a question of syntax.
> I am just learning to use list comprehension, which oc course, I find very
> helpful indeed.
> However, I am stuck with a specific problem of how to incorporate an else
> in a list comp-rehension. I cannot do it.
> The following snippet of code does what I need. But, perhaps I am solving
> this math error problem incorrectly.
> The problem is I am occasionally getting exactly zeros when I need to
> obtain the logarithm of the number.
> for i in range(len(cap)):
Using a for loop like this is generally a poor idea.
for aCap in cap:
is the more pythonic way. And also will help you translate to a list
> if cap[i] == 0.0:
> tmp = math.log(1.0)
Possibly lncap.append(math.log(1.0)) or even lncap.append(0) is simpler
Having said that above your present code, let me try to explain the thought
process behind constructing the list comprehension for your purpose. It is
possible that what you need is not an else in the list comprehension
lncap = [ f(aCap) for aCap in cap]
will be the starting point; where f() will need to provide either
math.log(aCap) or 0 as we saw earlier.
You can actually write an auxiliary function f that does just that; like say
if p == 0.0:
Or write the list comprehension as:
lncap = [ (math.log(aCap) if aCap > 0 else 0.0) for aCap in cap]
Hope this helps
More information about the Tutor