![](/img/trans.png)
[英]My program works well but I don't understand why? Something to do with functions and nested lists
[英]I don't understand lambdas functions in comprehension lists
我不明白理解列表中的 lambda 是如何工作的。
請幫助我理解這種機制,抱歉,我現在正在學習,網上能找到的解釋對我來說並不是很清楚。
def times_two(a): return a * 2
def times_three(a): return a * 3
numbers = [1, 2, 3, 4]
both_functions = [times_two, times_three]
for number in numbers:
print(list(map((lambda x: x(number)), both_functions)))
(lambda x: x(number))具體是做什么的,為什么會有第二個x,是什么參數?
其他例子:
is_even_list = [lambda a=x: a * 10 for x in range(0, 6)]
for item in is_even_list:
print(item())
為什么這里有一個a=x ,通常 lambdas 沒有只有一個參數?
最后一個:
A = [1, 2, 3, 4]
B = [lambda: _ for _ in A]
C = [_() for _ in B]
print(A)
print(B)
print(C)
_()在這里做什么?
您正在迭代的列表包含函數。 在迭代內部,您調用當前迭代項中的函數。
lambda x: x(number)
意味着它在x
中接收一個函數,然后以number
作為參數調用該函數。
for item in is_even_list:
print(item())
is_even_list
中的函數,並調用每個函數。
[_() for _ in B]
_
只是一個變量名,盡管通常它只用於不使用迭代項的迭代。 B
包含函數列表,因此它調用每個函數並返回結果列表。
(lambda x: x(number))
到底做什么
就理解而言,沒有什么特別的。 它是map()
的參數
為什么會有第二個x,是什么參數?
它是一個可調用的函數對象。
為什么這里有一個 a=x
它似乎正在定義一個帶有range()
參數的部分函數。 該語法對我來說是新的...
如果刪除=x
,則會出現錯誤missing 1 required positional argument: 'a'
,如果您定義了常規函數def foo(a):
並且只是在循環中調用了foo()
,則會出現相同的錯誤。
通常 lambdas 沒有只有一個參數
它們是內聯函數,所以不,它們可以有盡可能多的函數。
_() 做什么
_
只是一個變量。 它可以分配給可調用對象。 _()
調用名為_
的函數。
list(map((lambda x: x(number)), both_functions))
map 循環遍歷 both_functions 中定義的項目,這意味着對於每個數字,它循環遍歷 times_two 和 times_three 函數。 即:當數字為 1 時,它產生輸出 [times_two(1), times_three(1)] 等於 [2, 3]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.