【Python 笔记】神奇的匿名函数

来源:互联网 发布:淘宝网秋冬运动套装 编辑:程序博客网 时间:2024/05/20 03:04
Write a function, factory, that takes a number as its parameter and returns another function.The returned function should take an array of numbers as its parameter, and return an array of those numbers multiplied by the number that was passed into the first function.In the example below, 5 is the number passed into the first function. So it returns a function that takes an array and multiplies all elements in it by five.Translations and comments (and upvotes) welcome!
Examplefives = factory(5)          # returns a function - fivesmy_array = [1, 2, 3]fives(my_array)             # returns [5, 10, 15]

Python的神奇之处在于使用了匿名函数使得原本需要def两个函数的模块只写了一个函数,并且只用了一行~

def factory(x):    return lambda l: [x*i for i in l]    # Good Luck!


0 0
原创粉丝点击