Python中迭代器的创建与使用详解
作者:python收藏家
Python中的迭代器是一个对象,用于迭代可迭代对象,如列表,元组,字典和集合。Python迭代器对象使用iter()方法初始化。它使用next()方法进行迭代。
- iter():iter()方法用于迭代器的初始化。这将返回一个迭代器对象
- next():next方法返回可迭代对象的下一个值。当我们使用for循环来遍历任何可迭代对象时,它在内部使用iter()方法来获取迭代器对象,迭代器对象进一步使用next()方法进行迭代。此方法引发StopIteration以发出迭代结束的信号。
Python iter()示例
string = "GFG" ch_iterator = iter(string) print(next(ch_iterator)) print(next(ch_iterator)) print(next(ch_iterator))
输出
G
F
G
使用iter()和next()创建迭代器
下面是一个简单的Python迭代器,它创建了一个从10到给定限制的迭代器类型。例如,如果限制是15,则它会打印10 11 12 13 14 15。如果限制是5,则它不打印任何内容。
# An iterable user defined type class Test: # Constructor def __init__(self, limit): self.limit = limit # Creates iterator object # Called when iteration is initialized def __iter__(self): self.x = 10 return self # To move to next element. In Python 3, # we should replace next with __next__ def __next__(self): # Store current value ofx x = self.x # Stop iteration if limit is reached if x > self.limit: raise StopIteration # Else increment and return old value self.x = x + 1; return x # Prints numbers from 10 to 15 for i in Test(15): print(i) # Prints nothing for i in Test(5): print(i)
输出
10
11
12
13
14
15
使用iter方法迭代内置迭代器
在下面的迭代中,迭代状态和迭代器变量是内部管理的(我们看不到它),使用迭代器对象遍历内置的可迭代对象,如列表,元组,字典等。
# Iterating over a list print("List Iteration") l = ["geeks", "for", "geeks"] for i in l: print(i) # Iterating over a tuple (immutable) print("\nTuple Iteration") t = ("geeks", "for", "geeks") for i in t: print(i) # Iterating over a String print("\nString Iteration") s = "Geeks" for i in s : print(i) # Iterating over dictionary print("\nDictionary Iteration") d = dict() d['xyz'] = 123 d['abc'] = 345 for i in d : print("%s %d" %(i, d[i]))
输出
List Iteration
geeks
for
geeks
Tuple Iteration
geeks
for
geeks
String Iteration
G
e
e
k
s
Dictionary Iteration
xyz 123
abc 345
可迭代 vs 迭代器(Iterable vs Iterator)
Python中可迭代对象和迭代器不同。它们之间的主要区别是,Python中的可迭代对象不能保存迭代的状态,而在迭代器中,当前迭代的状态被保存。
注意:每个迭代器也是一个可迭代对象,但不是每个可迭代对象都是Python中的迭代器。
可迭代对象上迭代
tup = ('a', 'b', 'c', 'd', 'e') for item in tup: print(item)
输出
a
b
c
d
e
在迭代器上迭代
tup = ('a', 'b', 'c', 'd', 'e') # creating an iterator from the tuple tup_iter = iter(tup) print("Inside loop:") # iterating on each item of the iterator object for index, item in enumerate(tup_iter): print(item) # break outside loop after iterating on 3 elements if index == 2: break # we can print the remaining items to be iterated using next() # thus, the state was saved print("Outside loop:") print(next(tup_iter)) print(next(tup_iter))
输出
Inside loop:
a
b
c
Outside loop:
d
e
使用迭代器时出现StopIteration错误
Python中的Iterable可以迭代多次,但当所有项都已迭代时,迭代器会引发StopIteration Error。
在这里,我们试图在for循环完成后从迭代器中获取下一个元素。由于迭代器已经耗尽,它会引发StopIteration Exception。然而,使用一个可迭代对象,我们可以使用for循环多次迭代,或者可以使用索引获取项。
iterable = (1, 2, 3, 4) iterator_obj = iter(iterable) print("Iterable loop 1:") # iterating on iterable for item in iterable: print(item, end=",") print("\nIterable Loop 2:") for item in iterable: print(item, end=",") print("\nIterating on an iterator:") # iterating on an iterator object multiple times for item in iterator_obj: print(item, end=",") print("\nIterator: Outside loop") # this line will raise StopIteration Exception # since all items are iterated in the previous for-loop print(next(iterator_obj))
输出
Iterable loop 1:
1,2,3,4,
Iterable Loop 2:
1,2,3,4,
Iterating on an iterator:
1,2,3,4,
Iterator: Outside loop
Traceback (most recent call last):
File "scratch_1.py", line 21, in <module>
print(next(iterator_obj))
StopIteration
到此这篇关于Python中迭代器的创建与使用详解的文章就介绍到这了,更多相关Python迭代器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!