开发者

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?


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)


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜