Python - 迭代器

Python - 迭代器 首页 / Python3入门教程 / Python - 迭代器

Itertool是最令人惊奇的Python 3标准库之一。该库具有最酷的函数,没有错说它是Python编程语言的瑰宝。 Python为itertools提供了出色的文档,但是在本教程中,无涯教程将讨论itertools的一些重要和有用的函数或迭代器。

关于itertools的关键在于,该库的函数用于制作内存高效且精确的代码。

迭代器介绍

根据itertools的官方定义," 该模块实现了许多迭代器构造块,这些构造块的灵感来自APL,Haskell和SML 。"简而言之,迭代器的数量可以共同创建"迭代器代数",从而可以完成复杂的任务。 itertools中的函数用于生成更复杂的迭代器。举个例子:Python内置的zip()函数接受任意数量的可迭代参数。它遍历元组并返回其相应的元素。

a = [1,2,3]
b= ['a', 'b', 'c']
c = zip(a,b)
print(c)

输出:

[(1, 'a'), (2, 'b'), (3, 'c')]

在上面的代码中,传递了两个列表[1,2,3]和['a','b','c']在 zip()函数中可迭代。 这些列表一次返回一个元素。在 Python 中,一个实现 .__ iter __() .__ getitem __()方法的元素,称为iterable 。

Python iter()函数用于调用可迭代对象,并返回可迭代对象。

a = iter('Hello')
print(a)

输出:

<str_iterator object at 0x01505FA0>

Python zip()函数在其每个参数上调用 iter(),然后调用 next() (将结果合并到元组中)。

迭代器类型

itertools模块中有多种类型的迭代器。列表如下:

  • 无限迭代器
  • 组合迭代器
  • 终止迭代器

无限迭代器

在Python中,任何可以实现 for循环的对象都称为迭代器。列表,元组,集合,字典,字符串是迭代器的示例,但迭代器也可以是无限的,这种类型的迭代器称为无限迭代器

迭代器参数结果
count(start,step)start,[step]start,start+step,step+ 2 *step
cycle() P p0,p1,.... plast
repeat() elem [n] elem,elem,elem ......无休止或最多n次
  • count(start,step)  -  从开始值打印到无限。 step参数是可选的,如果将值提供给步数,则将跳过步骤数。考虑以下示例:
import itertools

for i in itertools.count(10,5):
    if i == 50:
        break
    else:
        print(i,end=" ")

输出:

10 15 20 25 30 35 40 45
  • cycle(iterable)  -  此迭代器从传递的参数开始按顺序打印所有值。它以循环方式打印值。考虑以下示例:
import itertools
temp = 0
for i in itertools.cycle("123"):
    if temp > 7:
        break
    else:
        print(i,end=' ')
        temp = temp+1

输出:

 1 2 3 1 2 3 1 2 3 1 2

示例-2:使用next()函数

import itertools

val = ['Java', 'T', 'Point']

iter = itertools.cycle(val)

for i in range(6):
    # Using next function
    print(next(iter), end = " ")

输出:

Java T Point Java T Point
  • repeat(val,num)  -  顾名思义,它会无限次重复打印传递的值。 num 参数是可选的。考虑以下示例:
 import itertools
 print("Printing the number repeadtly:")
 print(list(itertools.repeat(40,15)))

输出:

[40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40]

组合迭代器:递归生成器简化了复杂的组合结构。排列,组合和笛卡尔积是组合构造的示例。

在Python中,组合迭代器有四种类型:

  • Product()  -  用于计算可迭代输入的笛卡尔积。在此函数中,使用可选的 repeat 关键字参数来计算其自身的迭代产品。 repeat (关键字重复)代表重复的次数。它以已排序的元组的形式返回输出。考虑以下示例:
from itertools import product

print("We are computing cartesian product using repeat Keyword Argument:")
print(list(product([1, 2], repeat=2)))
print()

print("We are computing cartesian product of the containers:")
print(list(product(['Java', 'T', 'point'], '5')))
print()

print("We are computing product of the containers:")
print(list(product('CD', [4, 5])))

输出:

Computing cartesian product using repeat Keyword Argument:
[(1, 1), (1, 2), (2, 1), (2, 2)]

Computing cartesian product of the containers:
[('Java', '5'), ('T', '5'), ('point', '5')]

Computing product of the containers:
[('C', 4), ('C', 5), ('D', 4), ('D', 5)] 
  • Permutations()  -  用于生成可迭代对象的所有可能置换。每个元素的唯一性取决于其位置而不是值。它接受两个参数 iterable group_size 。如果group_size的值为 none 或未指定,则group_size变为可迭代的长度。
from itertools import permutations

print("Computing all permutation of the following list")
print(list(permutations([3,"Python"],2)))
print()

print("Permutations of following string")
print(list(permutations('AB')))
print()

print("Permutation of the given container is:")
print(list(permutations(range(4),2)))

输出:

Computing all permutation of the following list
[(3, 'Python'), ('Python', 3)]

Permutations of following string
[('A', 'B'), ('B', 'A')]

Permutation of the given container is:
[(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)]
  • Combinations()   -  用于打印集合的所有可能的组合(不替换),该组合作为参数以指定的组大小按排序顺序传递。
from itertools import combinations
print("Combination of list in sorted order(without replacement)",list(combinations(['B',3],2)))
print()

print("Combination of string in sorted order",list(combinations("ZX",2)))
print()

print("Combination of list in sorted order",list(combinations(range(20),1)))

输出:

Combination of list in sorted order(without replacement) [('B', 3)]
Combination of string in sorted order [('Z', 'X')]
Combination of list in sorted order [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)]
  • Combination_with_replacement()  -  它接受两个参数,第一个参数是r长度元组,第二个参数是重复。它从可迭代元素返回长度为n的子序列,并重复相同的过程。单独的元素可能会在 combination_with_replacement()中重复
from itertools import combinations_with_replacement

print("Combination of string in sorted order(with replacement) is:")
print(list(combinations_with_replacement("XY", 3)))
print()

print("Combination of list in sorted order(with replacement) is:")
print(list(combinations_with_replacement([4, 2], 3)))
print()

print("Combination of container in sorted order(with replacement) is:")
print(list(combinations_with_replacement(range(3), 2)))

输出:

Combination of string in sorted order(with replacement) is:
[('X', 'X', 'X'), ('X', 'X', 'Y'), ('X', 'Y', 'Y'), ('Y', 'Y', 'Y')]

Combination of list in sorted order(with replacement) is:
[(4, 4, 4), (4, 4, 2), (4, 2, 2), (2, 2, 2)]

Combination of container in sorted order(with replacement) is:
[(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]

终止迭代器

终止迭代器通常用于处理较小的输入序列,并根据迭代器中使用的方法的函数来生成输出。

终止迭代器有不同类型:

  • accumulate(iter,func)   -  它带有两个参数,第一个参数是可迭代的,第二个参数是在iterable的每次迭代中都将遵循的函数。如果未在 accumulate()迭代器中定义函数,则默认情况下会进行添加。输出可迭代取决于输入可迭代;如果输入iterable不包含任何值,则输出iterable也将为空。
import itertools
import operator

# 初始化list1
list1 = [1, 4, 5, 7, 9, 11]

# 使用accumulate()将打印元素的连续总和
print("The sum is : ", end="")
print(list(itertools.accumulate(list1)))

# 使用accumulate()将打印元素的连续乘法
print("The product is : ", end="")
print(list(itertools.accumulate(list1, operator.mul)))


# 使用accumulate()将打印元素的连续总和
print("The sum is : ", end="")
print(list(itertools.accumulate(list1)))

# 使用accumulate()将打印元素的连续乘法
print("The product is : ", end="")
print(list(itertools.accumulate(list1, operator.mul)))

输出:

The sum is : [1, 5, 10, 17, 26, 37]
The product is : [1, 4, 20, 140, 1260, 13860]
The sum is : [1, 5, 10, 17, 26, 37]
The product is : [1, 4, 20, 140, 1260, 13860]
  • chain(iter1,iter2) - 用于打印所有以链形式传递并在参数中声明的iterable值。考虑以下示例:
import itertools

# 声明list1
list1 = [1, 2, 3, 4]

# 声明list2
list2 = [1, 5, 6, 8]

# 声明list3
list3 = [9, 10, 11, 12]

# 使用将打印列表的所有元素的chain()函数
print("The output is : ", end="")
print(list(itertools.chain(list1, list2, list3)))

输出:

The output is: [1, 2, 3, 4, 1, 5, 6, 8, 9, 10, 11, 12]
  • dropwhile(func,seq) - 仅在 func 之后才开始打印字符。请考虑以下参数:
import itertools
# initializing list
list1 = [2, 4, 5, 7, 8]
# using dropwhile() iterator that will print start displaying after condition is false
print("The output is : ", end="")
print(list(itertools.dropwhile(lambda x: x % 2 == 0, list1)))

输出:

The output is  : [5, 7, 8]
  • filterfalse(func,seq) - 无涯教程可以用它的名字来假设它,因为此迭代器仅打印那些为传递的函数返回false的值。
import itertools

# 声明列表
list1 = [12, 14, 15, 27, 28]

# 使用将打印错误值的 filterfalse() 迭代器
print("The Output is: ", end="")
print(list(itertools.filterfalse(lambda x: x % 2 == 0, list1)))

输出:

The Output is : [15, 27]
  • islice(iterable,start,stop,step) - 根据给定位置对给定的可迭代对象进行切片。它分别接受四个参数,它们是可迭代的,集合,起始位置,结束位置和步骤(可选)。
import itertools
# 声明列表
list1 = [12, 34, 65, 73, 80, 19, 20]
# 使用将切片列表 acc 的 islice() 迭代器。给定论点从第 3 个索引开始打印到第 8 个跳过 2
print("The sliced list values are : ", end="")
print(list(itertools.islice(list1, 2, 8, 2)))

输出:

The sliced list values are : [34, 73, 19]
  • starmap(func,tuple list) - 需要两个参数;第一个参数是函数,第二个参数是列表,该列表由元组形式的元素组成。请考虑以下示例。
import itertools

# 声明包含元组作为元素的列表
list1 = [(10, 20, 15), (18, 40, 19), (53, 42, 90), (16, 12, 27)]

# 使用 starmap() 迭代器获取选择值 acc。发挥作用
# 选择所有元组值的最大值
print("The values acc. to function are : ", end="")
print(list(itertools.starmap(max, list1)))

输出:

The values acc. to function are : [20, 40, 90, 27]
  • takewhile(func,iterable) - 与 dropwhile()反之亦然。它将打印值,直到返回错误条件。考虑以下示例:
import itertools

# 定义列表
list1 = [20, 42, 64, 77, 8, 10, 20]

# takewhile() 迭代器用于打印值,直到条件返回 false。
print("Print until 1st false value returned : ", end="")
print(list(itertools.takewhile(lambda x: x % 2 == 0, list1)))

输出:

The list values until false value return : [20, 42, 64]
  • tee(iterator,count) - 将集合分为多个在参数中定义的迭代器。考虑以下示例:
import itertools

# 声明列表
li = [1, 2, 3, 4, 5, 6, 7]

# 在迭代器中存储列表
iti = iter(li)
# 使用 tee() 迭代器创建迭代器列表
# 创建具有相似值的 3 个迭代器的列表。
it = itertools.tee(iti, 3)
# 它将打印迭代器的对象
print(it)
print("The iterators are : ")
for i in range(0, 2):
    print(list(it[i]))

输出:

(<itertools._tee object at 0x01B88D88>, <itertools._tee object at 0x01B88DA8>, <itertools._tee object at 0x01B88BA8>)
The iterators are : 
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
  • zip_longest(iterable1,iterable2,fillval) - 交替打印iterable的值。如果迭代器之一打印了所有值,则剩余的值将由分配给填充值的值填充。
import itertools
print(" The combined value of iterrables is :")
print(*(itertools.zip_longest('Java', 'Tpoint', fillvalue='_')))

输出:

The combined value of iterables is :
('J', 'T') ('a', 'p') ('v', 'o') ('a', 'i') ('_', 'n') ('_', 't')

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Linux性能优化实战 -〔倪朋飞〕

重学前端 -〔程劭非(winter)〕

透视HTTP协议 -〔罗剑锋(Chrono)〕

深入浅出云计算 -〔何恺铎〕

数据中台实战课 -〔郭忆〕

系统性能调优必知必会 -〔陶辉〕

爆款文案修炼手册 -〔乐剑峰〕

深入剖析Java新特性 -〔范学雷〕

手把手带你写一个MiniSpring -〔郭屹〕

好记忆不如烂笔头。留下您的足迹吧 :)