📅  最后修改于: 2020-10-28 01:29:23             🧑  作者: Mango
Itertool是最令人惊奇的Python 3标准库之一。该库具有最酷的功能,并且可以说它是Python编程语言的瑰宝。 Python提供了关于itertools的出色文档,但是在本教程中,我们将讨论itertools的一些重要和有用的函数或迭代器。
关于itertools的关键在于,该库的功能用于制作内存高效且精确的代码。
学习Python的itertools之前,您应该有Python的迭代器和发电机的知识。在本文中,我们将介绍针对初学者以及专业人士的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()函数用于调用iterable并返回iterable的迭代器对象。
a = iter('Hello')
print(a)
输出:
Python zip()函数在其每个参数上调用iter(),然后通过将结果合并为元组来调用next()。
注意:如果您正在使用zip()函数和map()函数,则意味着您已经在使用itertools。您不需要明确地导入它。
itertools模块中有多种类型的迭代器。列表如下:
在Python,任何可以实现for循环的对象都称为迭代器。列表,元组,集合,字典,字符串是迭代器的示例,但是迭代器也可以是无限的,这种类型的迭代器称为无限迭代器。
Iterator | Argument | Results |
---|---|---|
count(start,step) | start, [step] | start, start+step, step+2*step |
cycle() | P | p0,p1,….plast |
repeat() | elem [,n] | elem, elem, elem,….endlessly or upto n times |
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
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
# initializing list 1
list1 = [1, 4, 5, 7, 9, 11]
# using accumulate() that will prints the successive summation of elements
print("The sum is : ", end="")
print(list(itertools.accumulate(list1)))
# using accumulate() that will prints the successive multiplication of elements
print("The product is : ", end="")
print(list(itertools.accumulate(list1, operator.mul)))
# using accumulate() that will prints the successive summation of elements
print("The sum is : ", end="")
print(list(itertools.accumulate(list1)))
# using accumulate() that will prints the successive multiplication of elements
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
# declaring list 1
list1 = [1, 2, 3, 4]
# declaring list 2
list2 = [1, 5, 6, 8]
# declaring list 3
list3 = [9, 10, 11, 12]
# using chain() function that will to print all elements of lists
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
# declaring list
list1 = [12, 14, 15, 27, 28]
# using filterfalse() iterator that will print false values
print("The Output is: ", end="")
print(list(itertools.filterfalse(lambda x: x % 2 == 0, list1)))
输出:
The Output is : [15, 27]
import itertools
# Declaring list
list1 = [12, 34, 65, 73, 80, 19, 20]
# using islice() iterator that will slice the list acc. to given argument
# starts printing from 3nd index till 8th skipping 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
# Declaring list that contain tuple as element
list1 = [(10, 20, 15), (18, 40, 19), (53, 42, 90), (16, 12, 27)]
# using starmap() iterator for selection value acc. to function
# selects max of all tuple values
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
# Defining a list
list1 = [20, 42, 64, 77, 8, 10, 20]
# takewhile() iterator is used to print values till condition return 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
# Declaring list
li = [1, 2, 3, 4, 5, 6, 7]
# storing list in iterator
iti = iter(li)
# using tee() iterator to create a list of iterators
# Creating list of 3 iterators having similar values.
it = itertools.tee(iti, 3)
# It will print object of iterator
print(it)
print("The iterators are : ")
for i in range(0, 2):
print(list(it[i]))
输出:
(, , )
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')
在本教程中,我们讨论了几个有用的迭代器以及itertools。