当前位置 博文首页 > boysoft2002的专栏:Python 四个可以和lambda结合使用的高阶函数
函数? | 用法 | 描述 |
filter | filter(function,sequence) | 返回给定序列中函数返回值的元素的列表,用于过滤序列,滤掉不符合条件的元素 |
map | map(function,sequence,…) | 创建由给定函数function应用到所提供列表sequence每个项目时返回的值组成的列表 |
sorted | sorted(iterable[,cmp][,key][,reverse]) | 从iterable的项目中返回一个新的排序后的列表。可选的参数和列表方法与sort中的相同 |
reduce | reduce(function,sequence[,initial]) | 依次从sequence中取一个元素,和上一次调用function的结果做参数,再次调用function |
前三个是内置函数,第四个函数在functools模块中,使用前需要先导入import。?
共同点:除sorted外都有一个参数是function,但sorted()的key参数可以是函数。
>>> help(filter)
Help on class filter in module builtins:
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).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
>>>
>>> help(map)
Help on class map in module builtins:
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).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
>>>
>>> help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
>>>
>>> from functools import reduce
>>> help(reduce)
Help on built-in function reduce in module _functools:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a 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). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
>>>
一、 filter()
用于过滤序列,序列中的每个元素作为参数传递给函数进行判断,返回True或者False,最后将返回True的元素放到新列表中。
...举例中
cs