前几天我写了一个类似于以下lambda表达式:
fetch = lambda x: myDictionaryVariable.get(x, "")
但现在我刚学到,你可以使用分号;
代替换行符来分隔Python语句,而且学到了即使使用冒号,也可以在一行上编写简单的语句。因此,我意识到我还可以写成这样:
def fetch(x): return myDictionaryVariable.get(x, "")
虽然我在这里没有使用;
,但如果有需要,我可以使用它,从而为我的一行函数提供更多功能。我可以这样写:
Not that I'm using the ;
here, but if I needed to I could, and thusly provide even more functionality for my 1-line function. I could write:
def strangeFetch(x): y = "unicorn"; return menu.get(x, y)
那么我为什么需要lambda?它们为什么是Python的一部分?在这种情况下,它们添加了什么?
strangeFetch()
很糟糕。 - Tim Peters