python标准库参考itertools:函数式序列数据高效处理利器-2: filter, islice, map, zip, filterfalse, zip_longest

简介

Python的实用性简单，提供了许多有用的函数和数据结构，使数据处理变得更容易，包括用来有效地循环数据的工具：itertools。

• filter()

• islice()

• map()

• zip()

filter() 和filterfalse()

filter()是内置函数。语法如下：

``````filter(function, iterable)
``````

``````>>> number_list = list(range(0,10))
>>> filtered_list = list(filter(lambda number: number % 2 == 0, number_list))
>>> print(filtered_list)
[0, 2, 4, 6, 8]
>>> [i for i in range(10) if i % 2 == 0]
[0, 2, 4, 6, 8]
>>> from itertools import filterfalse
>>> number_list = [x for x in range(0,10)]
>>> filtered_list = list(filterfalse(lambda number: number % 2 == 0, number_list))
>>> filtered_list
[1, 3, 5, 7, 9]
>>> def is_even(number):
...     return number%2==0
...
>>> filtered_list = list(filterfalse(is_even, number_list))
>>> filtered_list
[1, 3, 5, 7, 9]
``````

islice()函数

``````itertools.islice(iterable, start, end，step)
``````

``````>>> from itertools import islice
>>> old_string = "I need this, but not this"
>>> print(list(islice(old_string, 11)))
['I', ' ', 'n', 'e', 'e', 'd', ' ', 't', 'h', 'i', 's']
>>> print(list(islice(old_string, 7, 11)))
['t', 'h', 'i', 's']
``````

map()函数

``````map(function, iterable)
``````

map()是内置函数中，所以不需要导入任何东西。map用于对元素进行批量转换。

``````>>> list(map(lambda x: x**2, number_list))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 附加解包功能的starmap
>>> values = [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)]
>>> list(starmap(lambda x, y: (x, y, x * y), values))
[(0, 5, 0), (1, 6, 6), (2, 7, 14), (3, 8, 24), (4, 9, 36)]

``````

zip()和zip_longest()函数

``````zip(iterable_1, iterable_2, iterable_3...)
``````

``````>>> list(zip(range(3), range(4)))
[(0, 0), (1, 1), (2, 2)]
>>> list(zip_longest(range(3), range(4)))
[(0, 0), (1, 1), (2, 2), (None, 3)]
``````