Python iter()方法

python iter()方法 返回迭代器对象,用于将iterable转换为迭代器。

null

语法:iter(obj,sentinel)

参数:

  • obj: 必须转换为iterable的对象(通常是迭代器)。
  • 哨兵: 用于表示序列结束的值。

返回: 迭代器对象

迭代器的性质

  • 迭代对象通过内部计数变量记住迭代计数。
  • 迭代完成后,将引发StopIteration异常,并且无法将迭代计数重新分配为0。
  • 因此,它可以用来遍历容器一次。

Python iter()示例

示例1:Python迭代列表

Python3

# Python3 code to demonstrate
# working of iter()
# initializing list
lis1 = [ 1 , 2 , 3 , 4 , 5 ]
# printing type
print ( "The list is of type : " + str ( type (lis1)))
# converting list using iter()
lis1 = iter (lis1)
# printing type
print ( "The iterator is of type : " + str ( type (lis1)))
# using next() to print iterator values
print ( next (lis1))
print ( next (lis1))
print ( next (lis1))
print ( next (lis1))
print ( next (lis1))


输出:

The list is of type : The iterator is of type : 12345

示例2:带索引的Python迭代列表

Python3

# Python 3 code to demonstrate
# property of iter()
# initializing list
lis1 = [ 1 , 2 , 3 , 4 , 5 ]
# converting list using iter()
lis1 = iter (lis1)
# prints this
print ( "Values at 1st iteration : " )
for i in range ( 0 , 5 ):
print ( next (lis1))
# doesn't print this
print ( "Values at 2nd iteration : " )
for i in range ( 0 , 5 ):
print ( next (lis1))


输出:

Values at 1st iteration : 12345Values at 2nd iteration : 

例外情况:

Traceback (most recent call last):  File "/home/0d0e86c6115170d7cd9083bcef1f22ef.py", line 18, in     print (next(lis1))StopIteration
© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享