📜  Python Itertools

📅  最后修改于: 2020-10-28 01:29:23             🧑  作者: Mango

Python Itertools

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
  • count(start,stop) :从起始值打印到无限。步骤参数是可选的,如果该值被提供给步骤然后步骤数量将被跳过。考虑以下示例:
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() :用于生成可迭代对象的所有可能置换。每个元素的唯一性取决于其位置而不是值。它接受两个参数iterablegroup_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() :用于print容器的所有可能的组合(不替换),该组合作为参数以指定的组大小按排序顺序传递。
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的子序列,并重复相同的过程。单独的元素可以在combining_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不包含任何值,则输出iterable也将为空。
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]
  • chain(iter1,iter2) -用于print以链形式传递并在参数中声明的所有可迭代值。考虑以下示例:
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]
  • 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

# 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]
  • islice(iterable,start,stop,step) -根据给定位置将给定的iterable切片。它分别接受四个参数,它们是可迭代的,容器,起始位置,结束位置和步骤(可选)。
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]
  • starmap(func,元组列表) -需要两个参数;第一个参数是函数,第二个参数是包含元组形式的元素的列表。考虑以下示例。
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]
  • takewhile(func,iterable) -与dropwhile()相反它将print值,直到返回错误条件。考虑以下示例:
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]
  • tee(iterator,count) -它将容器分为多个在参数中定义的迭代器。考虑以下示例:
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]
  • 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')

在本教程中,我们讨论了几个有用的迭代器以及itertools。