能与lambda组合的五个常用内置函数

min(), max()

l = [1,-3,4,11,5,0.1]
print(min(l,key=lambda x:x**2))
l = [1,-3,4,-11,5,0.1]
print(max(l,key=lambda x:x**2))

注意min()、max()函数调用方式中,条件的传递使用 key作为关键字参数。

 


sorted()

 

l = [1,-3,4,-11,5,0.1]
print(sorted(l,key=lambda x:x**2,reverse=True))
help(sorted)

sorted()函数有两个关键字参数,key用来设置排序条件,reverse为False为降序,Ture为升序。


filter()

l = [1,-3,4,-11,5,0.1]
print(list(filter(lambda x:True if x%2==0 else False,l)))

filter()函数中func为位置参数,

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.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

<filter object at 0x00000000023511D0>

Process finished with exit code 0
help for filter()

 map()

l = [1,-3,4,0,-11,5,0.1]
print(list(map(lambda x:x**3,l)))

class map(object)
 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

[1, -27, 64, 0, -1331, 125, 0.0010000000000000002]
help for map()

 min(),max()返回值为原序列中的一个,sorter()返回序列与原序列值相同,只是顺序可能不一样;map(),filter()返回值为一个iterator(迭代器),可以用list()强制转换。

转载于:https://www.cnblogs.com/jeffhl/p/9759596.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值