📜  Python – Itertools.cycle()

📅  最后修改于: 2022-05-13 01:54:51.480000             🧑  作者: Mango

Python – Itertools.cycle()

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

有不同类型的迭代器

  1. 无限迭代器:
  2. 这些类型的迭代器产生无限序列。
  3. 短序列迭代器:
  4. 这些迭代器产生在某些迭代后终止的序列。
  5. 组合生成器函数:
  6. 这些生成器生成与输入参数相关的组合序列。

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