很简单,但我找不到合适的例子;所以我在这里问!
基本上我是这样的,resultList = map(if >0:do this, else:do this, listOfNumbers)
我该怎么做?
请您参考如下方法:
使用 lambda ( docs ) 函数。我使用了占位符函数 foo() 和 bar(),您必须将它们替换为“做这个”/“做那个”位。
resultList = map(lambda x: foo(x) if x > 0 else bar(x), listOfNumbers)
另一种方法,正如@hop 正确地说是 Python 中的首选方法,是使用列表理解。这甚至不需要使用 lambda 函数。
resultList = [foo(x) if x > 0 else bar(x) for x in listOfNumbers)
