簡體   English   中英

如何使用 apply 或 map 將 Python for 循環編寫為 lambda 函數?

[英]How to write a Python for loop as a lambda function with apply or map instead?

我將如何使用 lambda 函數編寫此代碼並應用或映射? 我看過幾篇博客文章等,但出於某種原因,我覺得我錯過了一些東西。 我認為應該很簡單。

for i in range(2,5):
    print(f'I only have {i} friends, but they are awesome.')

# I only have 2 friends, but they are awesome.
# I only have 3 friends, but they are awesome.
# I only have 4 friends, but they are awesome.

對於這個任務,循環就足夠了,但是如果由於某種原因你必須使用 lambda 和 map,你可以這樣做:

list(map(lambda x: print(f"I only have {x} friends, but they are awesome."), range(2, 5)))

map函數急切執行時,表達式需要包含在list()中,這意味着它在需要之前不會計算輸出。

你不只是使用 lambda 或 map 來執行上面的代碼,但是如果你只想用 lambda 或 map 來實現這一點,你需要將 map 對象轉換為列表。

list(map(lambda x:print(f'I only have {x} friends, but they are awesome.'), range(2,5)))

您根本不想使用 lambda,這是不可讀的。 Lambda 表達式不能包含循環、語句。 它們只能包含表達式(想想數學),但是,您的問題可以按如下方式解決。

s = 'I only have {} friends, but they are awesome.'
f = lambda x: list(map(print, map(s.format, x)))
f([1, 2, 3])

我們正在調用 list 來強制評估結果生成器,注意它被調用了 3 次 ([1, 2, 3]),因此,返回了 [None, None, None]。 結果生成器基本上是將打印函數映射到一個類似於 [s.format(1), s.format(2), s.format(3)] 的列表上

我只想向您展示如何做到這一點,但這是一種非常糟糕的方法。

我們可以對 fstrings 或百分比 % 做同樣的事情。

暫無
暫無

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

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