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

简介

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

本指南将向你展示如何使用itertools进行迭代。

  • filter()

接收序列或可迭代的对象,以及一个过滤条件(一个函数或lambda)。然后它测试序列中的每个元素是否符合过滤标准,只返回符合该标准的元素。

  • islice()

返回iterable的start和stop区间的生成器。

  • map()

创建可迭代的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)

如果只提供2个参数,则默认start为0,step默认为1。

>>> 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']

该功能和序列的切片功能很类似,故较少使用。

参考资料

  • 本文涉及的python测试开发库 谢谢点赞!
  • 本文相关海量书籍下载
  • https://pymotw.com/3/itertools/index.html
  • https://stackabuse.com/pythons-iteration-tools-filter-islice-map-and-zip

map()函数

语法如下:

map(function, iterable)

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

例如,你想把每个整数元素提高到2的幂。

>>> 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)]

你可能感兴趣的:(python标准库参考itertools:函数式序列数据高效处理利器-2: filter, islice, map, zip, filterfalse, zip_longest)