简体   繁体   English

高阶 Map Function 与 Lambda 表达式 Python

[英]High Order Map Function with Lambda Expression Python

I'm trying to write a higher order function that will take 2 lambda expressions and a list and will return the result.我正在尝试编写更高阶的 function ,它将采用 2 个 lambda 表达式和一个列表,并将返回结果。 I have my code below.我在下面有我的代码。

#Square
square = lambda x:x ** 2

#Mod_2
mod_2 = lambda x:x % 2

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

It looks very simple, and should be.它看起来很简单,而且应该如此。 This is the error I get:这是我得到的错误:

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'

Here's what the results should be:结果应该是这样的:

>>> 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]

This is NOT homework, and is simply and way to understand higher order functions better.这不是家庭作业,而是更好地理解高阶函数的简单方法。 Also, this is not a repeat of any other submission because this is fixing MY code, not how to do the problem itself.此外,这不是任何其他提交的重复,因为这是修复我的代码,而不是如何解决问题本身。 If it needs rethinking, please reply and tell me how.如果需要重新考虑,请回复并告诉我如何。 Thank you!谢谢!

Use a list comprehension:使用列表推导:

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

You can use a lambda here too:您也可以在这里使用 lambda:

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

Or just use the map() built-in.或者只使用内置的map()

map() is a built-in function. map() 是一个内置的 function。 Why are you redefining it?你为什么要重新定义它? Delete def map().删除 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