列表推导式中的 Lambda 函数 [英] Lambda function in list comprehensions

查看:49
本文介绍了列表推导式中的 Lambda 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么即使 flambda 函数是相同的,下面两个列表推导式的输出是不同的?

Why is the output of the following two list comprehensions different, even though f and the lambda function are the same?

f = lambda x: x*x
[f(x) for x in range(10)]

[lambda x: x*x for x in range(10)]

请注意,type(f)type(lambda x: x*x) 返回相同的类型.

Mind you, both type(f) and type(lambda x: x*x) return the same type.

推荐答案

第一个创建一个 lambda 函数并调用它十次.

The first one creates a single lambda function and calls it ten times.

第二个不调用函数.它创建了 10 个不同的 lambda 函数.它把所有这些都放在一个列表中.要使其等同于您需要的第一个:

The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need:

[(lambda x: x*x)(x) for x in range(10)]

或者更好:

[x*x for x in range(10)]

这篇关于列表推导式中的 Lambda 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆