#使用列表进行迭代 my_list = [4, 7, 0, 3] #get an iterator using iter() my_iter = iter(my_list) #get next element using next() #prints 4 print(next(my_iter)) #prints 7 print(next(my_iter)) #iterating through an entire list using next #output : 4 7 0 3 while True: try: print(next(my_iter)) except StopIteration: break
#using another example numbers = [1, 2, 3] # get an iterator using iter() n_iter = iter(numbers) while True: try: # get the next item print(next(n_iter)) except StopIteration: # if StopIteration is raised, break from loop break
#custom iterator class PowTwo:
'''Class to implement an iterator of powers of two''' def __init__(self, max = 0): self.n = 0 self.max = max def __iter__(self): return self def __next__(self): if self.n > self.max: raise StopIteration result = 2 ** self.n self.n += 1 return result #using the custom iterator a = PowTwo(4) i = iter(a) print(next(i)) print(next(i)) print(next(i)) print(next(i)) print(next(i))
#generator function containing the logic to create fibonacci numbers #the yield statement returns the next fibonacci number def fib(): a, b = 0, 1 while True: yield a a, b = b, a + b #using the generator #call the fib() generator function f = fib() #using next() to recursively print the fibonacci sequence print(next(f)) print(next(f)) print(next(f)) print(next(f)) print(next(f))
标签: 百度统计