这篇教程python中itertools模块使用小结写得很实用,希望能帮到您。 Python 内置的 itertools 模块包含了一系列用来产生不同类型迭代器的函数或类,这些函数的返回都是一个迭代器,我们可以通过 for 循环来遍历取值,也可以使用 next() 来取值。 itertools 模块提供的迭代器函数有以下几种类型: - 无限迭代器:生成一个无限序列,比如自然数序列 1, 2, 3, 4, ...;
- 有限迭代器:接收一个或多个序列(sequence)作为参数,进行组合、分组和过滤等;
- 组合生成器:序列的排列、组合,求序列的笛卡儿积等。
itertools高效循环下创建循环器的标准库 Infinite itertools,无限迭代器itertools.count(start=0, step=10) 默认返回一个从0开始,依次+10的自然数迭代器,如果你不停止,它会一直运行下去。 可以用start指定开始的位置,step是步长。 import itertoolsc = itertools.count(start=0, step=1)for i in c: print(i) # 0# 10# 20# 30# 40# 50# ... itertools.cycle(iterable) 传入一个可迭代对象,然后无限循环迭代。 import itertools# itertools.count()l = [1,2,3,4,5]c = itertools.cycle(l)for i in c: print(i)# 1# 2# 3# 4# 5# 1# 2# 3# 4# 5# ... itertools.repeat(p_object, times=None) 重复迭代一个对象p_object,如果不指定times,则会迭代无数次,也可以通过times参数指定迭代的次数。 import itertools# itertools.count()l = [1,2,3,4,5]c = itertools.repeat(l, 5)for i in c: print(i)# [1, 2, 3, 4, 5]# [1, 2, 3, 4, 5]# [1, 2, 3, 4, 5]# [1, 2, 3, 4, 5]# [1, 2, 3, 4, 5] Iterators terminating on the shortest input sequenceitertools.accumulate(iterable, func) 返回序列的累计值或者其他二进制函数。 import itertools# itertools.count()l = [1,2,3,4,5]c = itertools.accumulate(l)print(c)for i in c: print(i)# 1# 3# 6# 10# 15 accumulate()仍然返回的是一个迭代器,传一个list,在for循环中遍历打印的时候发现,它做了累加操作。(迭代第一个数,就是前一个数的和,迭代到第二个数时,就是前两个数的和,以此类推) 并且做递加操作时支持:list, tuple, str, set, dict 传入的是dict对象,那么会累加迭代dict的key: import itertools# itertools.count()d = {'a': 1, 'b': 2, 'c': 3}c = itertools.accumulate(d)print(c)for i in c: print(i)# <itertools.accumulate object at 0x000001F7A0A90E48># a# ab# abc itertools.chain(*iterables) chain()方法中的参数可以传入多个序列,而且只要是序列即可,不限定序列的数据类型。 如:迭代list, tuple, str三个序列 import itertoolsl = [1, 2, 3, 4, 5]t = (1, 2, 3, 4, 5)s = 'abcdefg'c = itertools.chain(l, t, s)print(c)for i in c: print(i)# <itertools.chain object at 0x0000026E64801448># 1# 2# 3# 4# 5# 1# 2# 3# 4# 5# a# b# c# d# e# f# g itertools 笛卡尔积import itertoolsd = [ [{"a": 1}, {"b": 2}], [{"c": 3}, {"d": 4}, {"e": 5}], [{"f": 6}, {"g": 7}]]print(*d)for i in itertools.product(*d): print(i)# [{'a': 1}, {'b': 2}] [{'c': 3}, {'d': 4}, {'e': 5}] [{'f': 6}, {'g': 7}]# ({'a': 1}, {'c': 3}, {'f': 6})# ({'a': 1}, {'c': 3}, {'g': 7})# ({'a': 1}, {'d': 4}, {'f': 6})# ({'a': 1}, {'d': 4}, {'g': 7})# ({'a': 1}, {'e': 5}, {'f': 6})# ({'a': 1}, {'e': 5}, {'g': 7})# ({'b': 2}, {'c': 3}, {'f': 6})# ({'b': 2}, {'c': 3}, {'g': 7})# ({'b': 2}, {'d': 4}, {'f': 6})# ({'b': 2}, {'d': 4}, {'g': 7})# ({'b': 2}, {'e': 5}, {'f': 6})# ({'b': 2}, {'e': 5}, {'g': 7}) 到此这篇关于python中的itertools模块简单使用的文章就介绍到这了,更多相关python itertools模块使用内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net! TensorFlow卷积神经网络MNIST数据集实现示例 TensorFlow深度学习另一种程序风格实现卷积神经网络 |