个性化阅读
专注于IT技术分析

Python Itertool模块用法完整指南

点击下载

本文概述

Python的Itertool是一个模块, 提供了可在迭代器上工作的各种功能, 以产生复杂的迭代器。此模块可作为一种快速的内存有效工具, 可单独使用或组合使用以形成迭代器代数.

例如, 假设有两个列表, 而你想将它们的元素相乘。有多种方法可以实现这一目标。可以使用朴素的方法, 即同时迭代两个列表的元素并将它们相乘。另一种方法可以使用map函数, 即通过多运算符作为map函数的第一个参数, Lists作为此函数的第二个和第三个参数。让我们看看每种方法花费的时间。

# Python program to demonstrate
# iterator module
  
  
import operator
import time
  
# Defining lists
L1 = [ 1 , 2 , 3 ]
L2 = [ 2 , 3 , 4 ]
  
# Starting time before map 
# function
t1 = time.time()
  
# Calculating result
a, b, c = map (operator.mul, L1, L2)
  
# Ending time after map
# function
t2 = time.time()
  
# Time taken by map function
print ( "Result:" , a, b, c)
print ( "Time taken by map function: %.6f" % (t2 - t1))
  
# Starting time before naive 
# method
t1 = time.time()
  
# Calculating result usinf for loop
print ( "Result:" , end = " " )
for i in range ( 3 ):
     print (L1[i] * L2[i], end = " " )
      
# Ending time after naive
# method
t2 = time.time()
print ( "\nTime taken by for loop: %.6f" % (t2 - t1))

输出如下:

Result: 2 6 12
Time taken by map function: 0.000005
Result: 2 6 12 
Time taken by for loop: 0.000014

在上面的示例中, 可以看出映射函数花费的时间大约是for循环花费的时间的一半。这表明itertools是快速的内存有效工具。

此模块提供的不同类型的迭代器是:

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

无限迭代器

Python中的迭代器是可以与”循环中’。 Python列表, 元组, 字典和集合都是内置迭代器的示例。但是迭代器对象不必用尽, 有时它可以是无限的。这种类型的迭代器称为无限迭代器.

Python提供了三种类型的无限迭代器:

计数(开始, 步进):

这个迭代器

从”开始”号开始打印并无限打印

。如果提到步骤, 则跳过数字, 否则默认为1。请参阅以下示例, 将其用于

对于

循环。

例子:

# Python program to demonstrate 
# infinite iterators 
    
import itertools 
    
# for in loop 
for i in itertools.count( 5 , 5 ): 
     if i = = 35 : 
         break
     else : 
         print (i, end = " " )

输出如下:

5 10 15 20 25 30

周期(可迭代):

该迭代器按顺序从传递的容器中打印所有值。重新启动

当所有元素以循环方式打印时, 从头开始重新打印

.

示例1:

# Python program to demonstrate 
# infinite iterators 
    
import itertools 
    
count = 0
    
# for in loop 
for i in itertools.cycle( 'AB' ): 
     if count> 7 : 
         break
     else : 
         print (i, end = " " ) 
         count + = 1

输出如下:

A B A B A B A B

示例2:使用下一个功能。

# Python program to demonstrate 
# infinite iterators 
    
import itertools 
    
l = [ 'Geeks' , 'for' , 'Geeks' ] 
    
# defining iterator 
iterators = itertools.cycle(l) 
    
# for in loop 
for i in range ( 6 ): 
        
     # Using next function 
     print ( next (iterators), end = " " )

组合迭代器

输出如下:

Geeks for Geeks Geeks for Geeks

重复(val, num):

该迭代器重复打印传递的值无限次。如果提到了可选关键字num, 则它将重复打印num次。

例子:

# Python code to demonstrate the working of   
# repeat()  
      
# importing "itertools" for iterator operations  
import itertools  
      
# using repeat() to repeatedly print number  
print ( "Printing the numbers repeatedly : " )  
print ( list (itertools.repeat( 25 , 4 )))

输出如下:

Printing the numbers repeatedly : 
[25, 25, 25, 25]

组合迭代器

用于简化组合结构(例如排列, 组合和笛卡尔积)的递归生成器称为组合迭代器。

在Python中, 有4个组合迭代器:

产品():

这个工具

计算笛卡尔积

输入可迭代项。为了计算一个可迭代对象与其自身的乘积, 我们使用可选的repeat关键字参数来指定重复次数。该函数的输出是按排序顺序的元组。

例子:

# import the product function from itertools module 
from itertools import product 
    
print ( "The cartesian product using repeat:" ) 
print ( list (product([ 1 , 2 ], repeat = 2 ))) 
print () 
    
print ( "The cartesian product of the containers:" ) 
print ( list (product([ 'geeks' , 'for' , 'geeks' ], '2' ))) 
print () 
    
print ( "The cartesian product of the containers:" ) 
print ( list (product( 'AB' , [ 3 , 4 ])))

输出如下:

The cartesian product using repeat:
[(1, 1), (1, 2), (2, 1), (2, 2)]

The cartesian product of the containers:
[('geeks', '2'), ('for', '2'), ('geeks', '2')]

The cartesian product of the containers:
[('A', 3), ('A', 4), ('B', 3), ('B', 4)]

排列():

排列()

顾名思义, 它习惯于

生成一个可迭代的所有可能的排列

。所有元素根据其位置而不是其值被视为唯一。此函数采用一个iterable和group_size, 如果未指定group_size的值或等于None, 则group_size的值将成为iterable的长度。

例子:

# import the product function from itertools module 
from itertools import permutations 
    
print ( "All the permutations of the given list is:" )  
print ( list (permutations([ 1 , 'geeks' ], 2 ))) 
print () 
   Terminating iterators
print ( "All the permutations of the given string is:" )  
print ( list (permutations( 'AB' ))) 
print () 
    
print ( "All the permutations of the given container is:" )  
print ( list (permutations( range ( 3 ), 2 )))

输出如下:

All the permutations of the given list is:
[(1, 'geeks'), ('geeks', 1)]

All the permutations of the given string is:
[('A', 'B'), ('B', 'A')]

All the permutations of the given container is:
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]

组合():

该迭代器打印

所有可能的组合(不更换)

以指定的组大小按排序顺序传递参数的容器的数量。

例子:

# import combinations from itertools module 
    
from itertools import combinations 
    
print ( "All the combination of list in sorted order(without replacement) is:" )  
print ( list (combinations([ 'A' , 2 ], 2 ))) 
print () 
    
print ( "All the combination of string in sorted order(without replacement) is:" ) 
print ( list (combinations( 'AB' , 2 ))) 
print () 
    
print ( "All the combination of list in sorted order(without replacement) is:" ) 
print ( list (combinations( range ( 2 ), 1 )))

输出如下:

All the combination of list in sorted order(without replacement) is:
[('A', 2)]

All the combination of string in sorted order(without replacement) is:
[('A', 'B')]

All the combination of list in sorted order(without replacement) is:
[(0, ), (1, )]

Combinations_with_replacement():

该函数从可迭代元素返回一个长度为n的子序列, 其中n是该函数确定该函数生成的子序列的长度的参数。

个别元素可能会重复

在groups_with_replacement函数中。

例子:

# import combinations from itertools module 
    
from itertools import combinations_with_replacement 
    
print ( "All the combination of string in sorted order(with replacement) is:" ) 
print ( list (combinations_with_replacement( "AB" , 2 ))) 
print () 
    
print ( "All the combination of list in sorted order(with replacement) is:" ) 
print ( list (combinations_with_replacement([ 1 , 2 ], 2 ))) 
print () 
    
print ( "All the combination of container in sorted order(with replacement) is:" ) 
print ( list (combinations_with_replacement( range ( 2 ), 1 )))

输出如下:

All the combination of string in sorted order(with replacement) is:
[('A', 'A'), ('A', 'B'), ('B', 'B')]

All the combination of list in sorted order(with replacement) is:
[(1, 1), (1, 2), (2, 2)]

All the combination of container in sorted order(with replacement) is:
[(0, ), (1, )]Terminating iterators

终止迭代器

终止迭代器用于处理短输入序列, 并根据所用方法的功能来产生输出。

终止迭代器的不同类型是:

累积(iter, func):

该迭代器接受两个参数, 可迭代的目标和目标中每次值迭代时将遵循的函数。如果未传递任何函数, 则默认情况下会进行添加。如果输入iterable为空, 则输出iterable也将为空。

例子:

# Python code to demonstrate the working of  
# accumulate()
  
  
import itertools 
import operator 
  
# initializing list 1 
li1 = [ 1 , 4 , 5 , 7 ] 
    
# using accumulate() 
# prints the successive summation of elements 
print ( "The sum after each iteration is : " , end = "") 
print ( list (itertools.accumulate(li1))) 
    
# using accumulate() 
# prints the successive multiplication of elements 
print ( "The product after each iteration is : " , end = "") 
print ( list (itertools.accumulate(li1, operator.mul))) 
    
# using accumulate() 
# prints the successive summation of elements 
print ( "The sum after each iteration is : " , end = "") 
print ( list (itertools.accumulate(li1))) 
    
# using accumulate() 
# prints the successive multiplication of elements 
print ( "The product after each iteration is : " , end = "") 
print ( list (itertools.accumulate(li1, operator.mul)))

输出如下:

The sum after each iteration is : [1, 5, 10, 17]
The product after each iteration is : [1, 4, 20, 140]
The sum after each iteration is : [1, 5, 10, 17]
The product after each iteration is : [1, 4, 20, 140]

链(iter1, iter2 ..):

此函数用于在其参数中一个接一个地打印可迭代目标中的所有值。

例子:

# Python code to demonstrate the working of  
# and chain() 
    
  
import itertools
  
# initializing list 1 
li1 = [ 1 , 4 , 5 , 7 ] 
    
# initializing list 2 
li2 = [ 1 , 6 , 5 , 9 ] 
    
# initializing list 3 
li3 = [ 8 , 10 , 5 , 4 ]
  
# using chain() to print all elements of lists 
print ( "All values in mentioned chain are : " , end = "") 
print ( list (itertools.chain(li1, li2, li3)))

输出如下:

All values in mentioned chain are : [1, 4, 5, 7, 1, 6, 5, 9, 8, 10, 5, 4]

chain.from_iterable():

该功能的实现方式与

链()

但此处的参数是列表或任何其他可迭代容器的列表。

例子:

# Python code to demonstrate the working of  
# chain.from_iterable()
  
  
import itertools
  
  
# initializing list 1 
li1 = [ 1 , 4 , 5 , 7 ] 
    
# initializing list 2 
li2 = [ 1 , 6 , 5 , 9 ] 
    
# initializing list 3 
li3 = [ 8 , 10 , 5 , 4 ] 
    
# intializing list of list 
li4 = [li1, li2, li3] 
  
# using chain.from_iterable() to print all elements of lists 
print ( "All values in mentioned chain are : " , end = "") 
print ( list (itertools.chain.from_iterable(li4)))

输出如下:

All values in mentioned chain are : [1, 4, 5, 7, 1, 6, 5, 9, 8, 10, 5, 4]

compress(iter, 选择器):

该迭代器根据作为其他参数传递的布尔列表值有选择地从传递的容器中选择要打印的值。打印与布尔值true相对应的参数, 否则将全部跳过。

例子:

# Python code to demonstrate the working of  
# and compress() 
  
  
import itertools
  
  
# using compress() selectively print data values 
print ( "The compressed values in string are : " , end = "") 
print ( list (itertools.compress( 'srcmini' , [ 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 1 , 0 , 0 , 0 , 0 ])))

输出如下:

The compressed values in string are : ['G', 'F', 'G']

dropwhile(func, seq):

此迭代器仅在函数之后才开始打印字符。 in参数首次返回false。

例子:

# Python code to demonstrate the working of  
# dropwhile()
  
  
import itertools
  
  
# initializing list  
li = [ 2 , 4 , 5 , 7 , 8 ] 
    
# using dropwhile() to start displaying after condition is false 
print ( "The values after condition returns false : " , end = "") 
print ( list (itertools.dropwhile( lambda x : x % 2 = = 0 , li)))

输出如下:

The values after condition returns false : [5, 7, 8]

filterfalse(func, seq):

顾名思义, 此迭代器仅输出对于传递的函数返回false的值。

例子:

# Python code to demonstrate the working of  
# filterfalse() 
    
  
import itertools 
    
# initializing list  
li = [ 2 , 4 , 5 , 7 , 8 ]
  
# using filterfalse() to print false values 
print ( "The values that return false to function are : " , end = "") 
print ( list (itertools.filterfalse( lambda x : x % 2 = = 0 , li)))

输出如下:

The values that return false to function are : [5, 7]

islice(可迭代, 开始, 停止, 步进):

该迭代器有选择地打印在其作为参数传递的可迭代容器中提到的值。该迭代器有4个参数, 可迭代的容器, 开始位置, 结束位置和步骤。

例子:

# Python code to demonstrate the working of  
# islice()
    
   
import itertools 
    
# initializing list  
li = [ 2 , 4 , 5 , 7 , 8 , 10 , 20 ] 
      
# using islice() to slice the list acc. to need 
# starts printing from 2nd index till 6th skipping 2 
print ( "The sliced list values are : " , end = "") 
print ( list (itertools.islice(li, 1 , 6 , 2 )))

输出如下:

The sliced list values are : [4, 7, 10]

starmap(功能, 元组列表):

此迭代器将一个函数和元组列表作为参数, 并从列表的每个元组中根据该函数返回值。

例子:

# Python code to demonstrate the working of  
# starmap() 
    
  
import itertools 
    
    
# initializing tuple list 
li = [ ( 1 , 10 , 5 ), ( 8 , 4 , 1 ), ( 5 , 4 , 9 ), ( 11 , 10 , 1 ) ] 
    
# using starmap() for selection value acc. to function 
# selects min of all tuple values 
print ( "The values acc. to function are : " , end = "") 
print ( list (itertools.starmap( min , li)))

输出如下:

The values acc. to function are : [1, 1, 4, 1]

takewhile(func, 可迭代):

该迭代器与dropwhile()相反, 它打印值, 直到函数第一次返回false为止。

例子:

# Python code to demonstrate the working of  
# takewhile()
    
  
import itertools 
    
# initializing list  
li = [ 2 , 4 , 6 , 7 , 8 , 10 , 20 ] 
    
# using takewhile() to print values till condition is false. 
print ( "The list values till 1st false value are : " , end = "") 
print ( list (itertools.takewhile( lambda x : x % 2 = = 0 , li )))

输出如下:

The list values till 1st false value are : [2, 4, 6]

发球台(重复, 计数):-

该迭代器将容器拆分为参数中提到的多个迭代器。

例子:

# Python code to demonstrate the working of  
# tee() 
    
  
import itertools 
    
# initializing list  
li = [ 2 , 4 , 6 , 7 , 8 , 10 , 20 ] 
    
# storing list in iterator 
iti = iter (li)  
    
# using tee() to make a list of iterators 
# makes list of 3 iterators having same values. 
it = itertools.tee(iti, 3 ) 
    
# printing the values of iterators 
print ( "The iterators are : " ) 
for i in range ( 0 , 3 ): 
     print ( list (it[i]))

输出如下:

The iterators are : 
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]

zip_longest(iterable1, iterable2, fillval):

该迭代器交替打印可迭代值。如果其中一个可迭代项已完全打印, 则剩余值将由分配给fillvalue的值填充。

例子:

# Python code to demonstrate the working of  
# zip_longest() 
    
  
import itertools 
    
# using zip_longest() to combine two iterables. 
print ( "The combined values of iterables is  : " ) 
print ( * (itertools.zip_longest( 'GesoGes' , 'ekfrek' , fillvalue = '_' )))

输出如下:

The combined values of iterables is  : 
('G', 'e') ('e', 'k') ('s', 'f') ('o', 'r') ('G', 'e') ('e', 'k') ('s', '_')

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python Itertool模块用法完整指南

评论 抢沙发

评论前必须登录!