一、Map函数
map函数是python内置的函数(工厂函数),使用help(map)
查看map函数的说明信息。
>>> help(map)
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:
……
map功能描述:生成一个迭代器,该迭代器使用来自每个iterable的参数计算函数。当最短的iterable耗尽时停止。
map函数必须传入两个参数:
- func:函数。
- iterables:可迭代对象(可以被for循环遍历的对象),list、tuple、dict、生成器、迭代器等。
map返回的对象是Iterator,是惰性序列,实际计算行为在调用next函数处理的时候才进行。
map函数将返回一个迭代器(iterator)对象。
>>> from collections import Iterator
>>>a = map(lambda x:x, range(3))
>>> isinstance(a, Iterator)
True
当对返回的迭代器使用next方法时会将传进来的可迭代对象的一个对象放到函数中进行处理,并返回结果,当遍历完最后一个对象,再使用next方法时会抛出StopIteration异常。
>>> next(a)
0
>>> next(a)
1
>>> next(a)
2
>>> next(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
二、Filter函数
运行help(filter)
查看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.
filter功能描述:从iterable中获取对象(item)放进函数中进行处理,只保留函数返回的结果可判断为True的项(item)。如果第一个参数为None,则返回iterable中判断为True的对象。
function函数要求传入两个参数:
- function or None:函数或者None;
- iterable:可迭代对象(可以被for循环遍历的对象),list、tuple、dict、生成器、迭代器等。
filter返回的对象是Iterator,是惰性序列,实际过滤行为在调用next函数处理的时候才进行。
filter函数将返回一个迭代器(iterator)对象。
以下函数将过滤偶数并返回一个迭代器。
>>> a = filter(lambda x: x % 2 == 0, range(4))
>>> type(a)
<class 'filter'>
>>> isinstance(a, Iterator)
True
>>> print(list(a))
[0, 2]
三、Sorted函数
运行help(sorted)
查看filter函数的说明信息。
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.
sorted函数功能描述:以列表的形式,将iterable中的对象按升序进行排序后的结果返回。sorted函数允许自定义函数来处理iterable中的每个结果,按函数返回的结果进行排序。
sorted函数至少传进一个参数:
- iterable:可迭代对象(可以被for循环遍历的对象),list、tuple、dict、生成器、迭代器等。
- key:可选参数,默认为None,可以指向一个函数。
- reverse:默认为False,如果设置为True,将逆转排序后的结果。
使用filter函数对列表进行排序:
>>> a = [2,1,7,3,6,9,4]
>>> b = sorted(a)
>>> print(b)
[1, 2, 3, 4, 6, 7, 9]
需要进行降序排序,只需将reverse设置为True:
>>> a = [2,1,7,3,6,9,4]
>>> b = sorted(a, reverse=True)
>>> print(b)
[9, 7, 6, 4, 3, 2, 1]
自定义函数将奇、偶数分开:
>>> a = [2,1,7,3,6,9,4]
>>> def func1(x):
... return x % 2 == 0
>>> b = sorted(a, key=func1)
>>> print(b)
[1, 7, 3, 9, 2, 6, 4]