Bolster
Bolster

Reputation: 7906

Python map() with cases

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

Answers (3)

moinudin
moinudin

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

Alexander Artemenko
Alexander Artemenko

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

Fred Foo
Fred Foo

Reputation: 363607

resultList = [foo(x) if x > 0 else bar(x) for x in listOfNumbers]

Upvotes: 3

Related Questions