简体   繁体   English

如何使用 apply 或 map 将 Python for 循环编写为 lambda 函数?

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

How would I write this code using a lambda function and apply or map?我将如何使用 lambda 函数编写此代码并应用或映射? I have looked at several blog posts, etc., but for some reason I feel like I am missing something.我看过几篇博客文章等,但出于某种原因,我觉得我错过了一些东西。 I think it should be really simply.我认为应该很简单。

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.

A loop is good enough for this task, but if for some reason you must use lambda and map, you can do it like this:对于这个任务,循环就足够了,但是如果由于某种原因你必须使用 lambda 和 map,你可以这样做:

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

The expression needs to be wrapped in list() as the map function is eagerly executed, which means it doesn't calculate the output until it is needed.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)))

You don't want to use lambdas at all, unreadable.您根本不想使用 lambda,这是不可读的。 Lambda expressions can't contain loops, statements. Lambda 表达式不能包含循环、语句。 They can contain expressions only (think maths), However, Your problem can be approached like the following.它们只能包含表达式(想想数学),但是,您的问题可以按如下方式解决。

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

We're calling list to force evaluate the result generator, note that it's called 3 times ([1, 2, 3]) and therefore, there're [None, None, None] returned.我们正在调用 list 来强制评估结果生成器,注意它被调用了 3 次 ([1, 2, 3]),因此,返回了 [None, None, None]。 The result generator is basically mapping print function on a list that looks like [s.format(1), s.format(2), s.format(3)]结果生成器基本上是将打印函数映射到一个类似于 [s.format(1), s.format(2), s.format(3)] 的列表上

I wanted only to show you how to do it, but this is a very bad approach.我只想向您展示如何做到这一点,但这是一种非常糟糕的方法。

We can do the same with fstrings or percent %.我们可以对 fstrings 或百分比 % 做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM