【Python】Itertools.cycle()用法及代码示例

让迭代器可以无限循环迭代。

迭代器定义为对象类型,其中包含可以使用循环访问或迭代的值。 内置与Python一起提供了不同的迭代器,例如列表,集合等。Itertools是Python模块,其中包含一些用于使用迭代器生成序列的内置函数。该模块提供了在迭代器上工作以生成复杂迭代器的各种功能。该模块可作为一种快速的内存有效工具,可单独使用或组合使用以形成迭代器代数。

有不同类型的迭代器

  • 无限迭代器:

    这些类型的迭代器会产生无限序列。

  • 短序列迭代器:

    这些迭代器产生在某些迭代之后终止的序列。

  • 组合发电机的功能:

    ​​​​​​​这些生成器组合产生与输入自变量相关的序列。

Itertools.cycle()

  • 函数仅接受一个参数作为输入,可以像列表,字符串,元组等
  • 该函数返回迭代器对象类型
  • 在函数的实现中,返回类型为yield,它在不破坏局部变量的情况下挂起函数执行。由生成中间结果的生成器使用
  • 它遍历输入自变量中的每个元素并产生它并重复循环,并产生一个无穷大的自变量序列

下面提到的Python程序说明了循环功能的功能。它以字符串类型作为参数并产生无限序列。

import itertools 
  
  
# String for sequence generation 
Inputstring ="Geeks"
  
# Calling the function Cycle from 
# itertools and passing string as  
#an argument and the function returns 
# the iterator object 
StringBuffer = itertools.cycle(Inputstring) 
SequenceRepeation = 0
SequenceStart = 0
SequenceEnd = len(Inputstring) 
  
for output in StringBuffer:
    if(SequenceStart == 0):
        print("Sequence % d"%(SequenceRepeation + 1)) 
  
    # Cycle function iterates through each 
    # element and produces the sequence  
    # and repeats it the sequence 
    print(output, end =" ") 
  
    # Checks the End of the Sequence according  
    # to the give input argument 
    if(SequenceStart == SequenceEnd-1):
          
        if(SequenceRepeation>= 2):
            break
        else:
            SequenceRepeation+= 1
            SequenceStart = 0
            print("\n") 
    else:
        SequenceStart+= 1

输出:

Sequence  1
G e e k s 

Sequence  2
G e e k s 

Sequence  3
G e e k s

itertools.cycle函数还可以与Python列表一起使用。下面提到的Python程序说明了该功能。它以Python列表作为参数并产生无限序列。

import itertools 
  
  
# List for sequence generation 
Inputlist = [1, 2, 3] 
  
# Calling the function Cycle from 
# itertools and passing list as  
# an argument and the function  
# returns the iterator object 
ListBuffer = itertools.cycle(Inputlist) 
SequenceRepeation = 0
SequenceStart = 0
SequenceEnd = len(Inputlist) 
  
for output in ListBuffer:
    if(SequenceStart == 0):
        print("Sequence % d"%(SequenceRepeation + 1)) 
  
    # Cycle function iterates through  
    # each element and produces the  
    # sequence and repeats it the sequence 
    print(output, end =" ") 
  
    # Checks the End of the Sequence according 
    # to the give input argument 
    if(SequenceStart == SequenceEnd-1):
          
        if(SequenceRepeation>= 2):
            break
        else:
            SequenceRepeation+= 1
            SequenceStart = 0
            print("\n") 
    else:
        SequenceStart+= 1

输出:

Sequence  1
1 2 3 

Sequence  2
1 2 3 

Sequence  3
1 2 3 

猜你喜欢

转载自blog.csdn.net/u013066730/article/details/114278749