繁体   English   中英

高阶 Map Function 与 Lambda 表达式 Python

[英]High Order Map Function with Lambda Expression Python

我正在尝试编写更高阶的 function ,它将采用 2 个 lambda 表达式和一个列表,并将返回结果。 我在下面有我的代码。

#Square
square = lambda x:x ** 2

#Mod_2
mod_2 = lambda x:x % 2

def map(f,x):
  return f(x)

它看起来很简单,而且应该如此。 这是我得到的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "main.py", line 8, in map
    return f(x)
  File "main.py", line 2, in <lambda>
    square = lambda x:x ** 2
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

结果应该是这样的:

>>> map(square, [1, 2, 3, 4])
[1, 4, 9, 16]
>>> map(square, [])
[]
>>> map(mod_2, range(1, 11))
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]

这不是家庭作业,而是更好地理解高阶函数的简单方法。 此外,这不是任何其他提交的重复,因为这是修复我的代码,而不是如何解决问题本身。 如果需要重新考虑,请回复并告诉我如何。 谢谢!

使用列表推导:

def map(f,x):
    return [f(i) for i in x]

您也可以在这里使用 lambda:

map = lambda f, x: [f(i) for i in x]

或者只使用内置的map()

map() 是一个内置的 function。 你为什么要重新定义它? 删除 def map()。

#Square
square = lambda x: x**2

#Mod_2
mod_2 = lambda x:x % 2

r1 = list(map(square, [1, 2, 3, 4]))
r2 = list(map(mod_2, range(1, 11)))

暂无
暂无

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

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