python标准库参考itertools:函数式序列数据高效处理利器-1

简介

python标准库参考itertools:函数式序列数据高效处理利器-1

Python 有很多内置工具,允许我们迭代和转换数据。比如itertools模块,它提供了几个方便的迭代函数。每个迭代器构建函数都可以单独使用,也可以组合使用。

该模块的灵感来自于函数式语言,如APL、Haskell 和 SPL。

Iterable vs Iterator

iterable是可迭代的对象。当使用iter()函数时,生成迭代器。一般来说,大多数序列都是可迭代的,如列表、元组、字符串等。

iterator来迭代可迭代的序列,迭代器也可以迭代自己,可以通过使用next()方法来实现,传入我们要遍历的迭代器。

>>> list = [1,2,3,4,5]
>>> iterator = iter(list)
>>> print(iterator)

>>> print(next(iterator))
1

count()

python标准库参考itertools:函数式序列数据高效处理利器-1

count(start, step)函数创建了代器,用于生成均匀间隔的值,它们之间的空间由step参数定义。start参数定义了迭代器的起始值--默认情况下,这些参数被设置为start=0,step=1。

如果没有中断条件,count()函数将无限计数(受限于内存)。

>>> from itertools import count
>>> 
>>> iterator_count = count(start=0, step=5)
>>> 
>>> for i in iterator_count:
...     if(i == 25):
...         break
...     print(i)
... 
0
5
10
15
20

该函最常与其他函数一起使用。

例如,当使用zip()将一个列表的多个项目压缩在一起时,你可能想通过一个位置索引来注释它们。在压缩的时候,我们会用count()来生成这些索引的值。

>>> from itertools import count
>>> 
>>> list = ['John', 'Marie', 'Jack', 'Anna']
>>> for i in zip(count(), list):
...     print(i)
... 
(0, 'John')
(1, 'Marie')
(2, 'Jack')
(3, 'Anna')
>>> for i in zip(range(10), list):
...     print(i)
... 
(0, 'John')
(1, 'Marie')
(2, 'Jack')
(3, 'Anna')

是不是和内置函数range和类似,只是更简单一点。因为这个原因,很多人使用range而不是count。不过count支持小数:

>>> for i in zip(count(1, 0.1), ['a', 'b', 'c']):
...     print('{:.2f}: {}'.format(*i))
... 
1.00: a
1.10: b
1.20: c

cycle()函数

cycle()函数接受iterable并生成一iterator,它包含了迭代器的所有元素。
一旦我们迭代到元素的末尾,我们就开始迭代这些副本。在迭代副本的过程中,会产生新的副本。一旦第一组副本用完,我们就迭代新的一组。这个过程无限重复。

使用cycle(),特别是对较长的序列来说,是非常耗费内存的。小心无限的、递归的创建逻辑,因为会耗尽内存。

from itertools import cycle

list = [1,2,3,4]
iterator = cycle(list)

for i in iterator:
    print(i)

结果

1
2
3
4
1
2
3
4
...

直到我们终止程序或耗尽内存。也就是说--你应该始终为cycle()函数设置退出/终止条件。

repeat()函数

cycle占用内存太多,可以用repeat控制数量

>>> from itertools import repeat
>>> 
>>> for i in repeat('over-and-over', 5):
...     print(i)
... 
over-and-over
over-and-over
over-and-over
over-and-over
over-and-over

# repeat在只传入一个参数的时候,表示循环该值

>>> for i in map(lambda x, y: (x, y, x * y), repeat(2), range(5)):
...     print('{:d} * {:d} = {:d}'.format(*i))
... 
2 * 0 = 0
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8

chain()函数

chain()函数用于将多个iterable连接一起,通过生成一个迭代器,一个接一个地依次遍历它们。

from itertools import chain

result = list(chain([1, 2, 3], 
        ["one", "two", "three"], 
        "String", 
        ("this", "is", "a", "tuple")))
        
print(result)

结果

[1, 2, 3, 'one', 'two', 'three', 'S', 't', 'r', 'i', 'n', 'g', 'this', 'is', 'a', 'tuple']

更多例子

from itertools import chain

result2 = list(chain(["one", "two", "three"]))
result3 = list(chain.from_iterable(["one", "two", "three"]))

print(result2)
print(result3)

number_list = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
result = list(chain.from_iterable(number_list))
print(sum(result))

结果

['one', 'two', 'three']
['o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e']
45
python标准库参考itertools:函数式序列数据高效处理利器-1

展开阅读全文

页面更新:2024-03-13

标签:递归   序列   函数   组合   遍历   高效   小数   副本   利器   模块   索引   元素   定义   内存   条件   参数   标准   数据   列表   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top