匿名函数与内置函数

匿名 (未验证) 提交于 2019-12-02 23:48:02

匿名函数

fun = lambda x : x*2  print(fun) print(fun(2))  >>> <function <lambda> at 0x10b9197a0> >>> 4  说明: fun ->函数名 lambda ->相当于定义函数的def, 匿名函数的定义就用lambda x -> 匿名函数的形参 x * 2 ―> 匿名函数返回值

匿名函数的特点:临时存在,用完就没了

匿名函数的应用:一般与内置函数一起连用。

name_list = ['jason', 'tank', 'egon'] salary_list = [100, 200, 300] dic = {k:v for k, v in zip(name_list, salary_list)}  #找出dic中工资最高的那个人的人名 print(max(dic, key=lambda name: dic[name]))  >>>egon

内置函数

filter:

class filter(object):     """     filter(function or None, iterable) --> filter object          Return an iterator yielding those items of iterable for which function(item)     is true. If function is None, return the items that are true.  def fun(x):     return x % 2  print(list(filter(fun, [1,2,3,4])))  >>> [1, 3]

def fun(x):     if x % 2:         return False     return True  print(list(filter(fun, [1,2,3,4])))  # (item for item in iterable if function(item))  >>>[2, 4]

map:

map(function,iterable,...)

Return an iterator that appliesfunctioniterable, yielding the results.

如果有多个iterable, 取多组iterable的第一个、第二个...组成一个个元组传给function。

With multiple iterables, the iterator stops when the shortest iterable is exhausted

只有一个iterable,map相当于把function作用到iterable的每一个元素上。

iterable_list = [1,2,3,12]  print(list(map(lambda x:x*x, iterable_list)))  >>> [1, 4, 9, 144]

不算是内置函数的reduce

functools.reduce(function,iterable[,initializer])
Applyfunctionsequence, from left to right,
so as to reduce the sequence to a single value.
For example,calculates((((1+2)+3)+4)+5).
from functools import reduce  l = [1, 2, 3, 4] def func(x, y):     return x * y  res = reduce(func, l) print(res)  >>> 24

zip:

  把每一个迭代器的元素聚合起来,返回一个元组

zip(*iterables)

1、Make an iterator that aggregates elements from each of the iterables.

  Returns an iterator of tuples

x = [1, 2, 3, 4] y = [1, 2, 3, 4] res = zip(x, y) print(*res)  >>> (1, 1) (2, 2) (3, 3) (4, 4)
x = [1, 2, 3, 4]y = [1, 2, 3, 4]res = zip(x, y)print(list(zip(*res)))>>> [(1, 2, 3, 4), (1, 2, 3, 4)]

2、The iterator stops when the shortest input iterable is exhausted.

3、With a single iterable argument, it returns an iterator of 1-tuples.

4、With no arguments, it returns an empty iterator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!