簡體   English   中英

為什么我不能在 Python lambda 中使用元組打包?

[英]Why can't I use tuple packing in a Python lambda?

當我在 Python 中嘗試以下操作時:

>>> lambda x: x, x * 2, x * 3

它給出了一個NameError

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

當它在常規函數中工作時,為什么它不起作用,就像下面的代碼一樣?

def function(x):
    return x, x * 2, x * 3

function(1)  # Returns (1, 2, 3)

首先,您必須記住 lambda 是函數,而函數是一等公民。 這意味着您可以像使用任何其他 object 一樣使用它們,包括將它們放入元組中。 事實證明,Python 正在嘗試使用元組打包,只是不像您期望的那樣。 請參閱以下代碼片段:

>>> lambda: 1, 2, 3
(<function <lambda> at 0x000001A944F2F040>, 2, 3)

如您所見,正如您所料,它將 lambda 打包成一個元組。 this is because it is easier to explicitly return a tuple (ie lambda: (1, 2, 3) , or lambda x: (x, x * 2, x * 3) ) then to change the Python syntax altogether (which already packs將 lambda 轉換為元組,而不是將元組轉換為 lambda)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM