Itertool是最令人惊奇的Python 3标准库之一。该库具有最酷的函数,没有错说它是Python编程语言的瑰宝。 Python为itertools提供了出色的文档,但是在本教程中,无涯教程将讨论itertools的一些重要和有用的函数或迭代器。
关于itertools的关键在于,该库的函数用于制作内存高效且精确的代码。
根据itertools的官方定义," 该模块实现了许多迭代器构造块,这些构造块的灵感来自APL,Haskell和SML 。"简而言之,迭代器的数量可以共同创建"迭代器代数",从而可以完成复杂的任务。 itertools中的函数用于生成更复杂的迭代器。举个例子:Python内置的zip()函数接受任意数量的可迭代参数。它遍历元组并返回其相应的元素。
输出:
[(1, 'a'), (2, 'b'), (3, 'c')]
在上面的代码中,传递了两个列表[1,2,3]和['a','b','c']在 zip()函数中可迭代。 这些列表一次返回一个元素。在 Python 中,一个实现 .__ iter __()或 .__ getitem __()方法的元素,称为iterable 。
Python iter()函数用于调用可迭代对象,并返回可迭代对象。
输出:
<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次 |
输出:
10 15 20 25 30 35 40 45
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
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中,组合迭代器有四种类型:
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)]
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)]
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,)]
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)]
终止迭代器通常用于处理较小的输入序列,并根据迭代器中使用的方法的函数来生成输出。
终止迭代器有不同类型:
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]
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]
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]
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]
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]
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]
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]
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]
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')
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)