📜  Python iter() 方法

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

Python iter() 方法

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

迭代器的属性

  • 迭代对象通过内部计数变量记住迭代计数。
  • 迭代完成后,它会引发 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))


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))


输出
The list is of type : 
The iterator is of type : 
1
2
3
4
5

示例 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 : 
1
2
3
4
5
Values at 2nd iteration : 

实际异常(错误):

Traceback (most recent call last):
  File "/home/0d0e86c6115170d7cd9083bcef1f22ef.py", line 18, in 
    print (next(lis1))
StopIteration