能与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()强制转换。

posted on 2018-10-09 15:42  末末的爸爸  阅读(123)  评论(0编辑  收藏  举报

导航