📜  Python中的迭代器

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

Python中的迭代器

Python中的迭代器是一个对象,用于迭代列表、元组、字典和集合等可迭代对象。使用iter()方法初始化迭代器对象。它使用next()方法进行迭代。

  1. __iter(iterable)__为迭代器初始化而调用的方法。这将返回一个迭代器对象
  2. next ( Python 3 中的 __next__ ) next 方法返回可迭代对象的下一个值。当我们使用 for 循环遍历任何可迭代对象时,它在内部使用 iter() 方法获取一个迭代器对象,该对象进一步使用 next() 方法进行迭代。此方法引发一个 StopIteration 来表示迭代的结束。

迭代器如何在Python中真正起作用

Python3
# Here is an example of a python inbuilt iterator
# value can be anything which can be iterate
iterable_value = 'Geeks'
iterable_obj = iter(iterable_value)
 
while True:
    try:
 
        # Iterate by calling next
        item = next(iterable_obj)
        print(item)
    except StopIteration:
 
        # exception will happen when iteration will over
        break


Python3
# A simple Python program to demonstrate
# working of iterators using an example type
# that iterates from 10 to given value
 
# 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)


Python3
# Sample built-in iterators
 
# 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]))


输出 :

G                                                                                                                                                                            
e                                                                                                                                                                            
e                                                                                                                                                                            
k                                                                                                                                                                            
s


下面是一个简单的Python自定义迭代器,它创建从 10 迭代到给定限制的迭代器类型。例如,如果限制为 15,则打印 10 11 12 13 14 15。如果限制为 5,则不打印任何内容。

Python3

# A simple Python program to demonstrate
# working of iterators using an example type
# that iterates from 10 to given value
 
# 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


在接下来的迭代中,for循环在内部(我们看不到它)使用迭代器对象来遍历可迭代对象

Python3

# Sample built-in iterators
 
# 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