Reputation: 7906
Simple enough but I can't find a decent example; so I asked here!
Basically what I was is, resultList = map(if >0:do this, else:do this, listOfNumbers)
How do I do that?
Upvotes: 1
Views: 341
Reputation: 138357
Use a lambda
(docs) function. I've used placeholder functions foo()
and bar()
which you'll have to replace with your "do this" / "do that" bits.
resultList = map(lambda x: foo(x) if x > 0 else bar(x), listOfNumbers)
An alternative, which as @hop rightfully says is the preferred method in Python, is to use a list comprehension. This doesn't even need the use of a lambda
function.
resultList = [foo(x) if x > 0 else bar(x) for x in listOfNumbers)
Upvotes: 7
Reputation: 22786
The answer is simple: DON'T TO THIS.
Really. Be friendly to those guy who have to read code after you. Write it in few lines, like that:
def choose_value(x):
if x > 0:
return blah(x)
return minor(x)
results = map(choose_value, list_of_numbers)
This is much more readable and reusable on my taste.
Upvotes: 4
Reputation: 363607
resultList = [foo(x) if x > 0 else bar(x) for x in listOfNumbers]
Upvotes: 3