匿名函数与内置函数

匿名函数

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]

 理解重点:

  返回值为:  (item for item in iterable if function(item))

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 applies function to every item of iterable, yielding the results.

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

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

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

相当于:( function(item)  for item in 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]) Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 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

 

转载于:https://www.cnblogs.com/KbMan/p/11182758.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值