当前分类:python>>正文

优化迭代器:深入了解Python的next()函数使用方法

来源:互联网   更新时间:2023年7月24日  

Python 笔记

一、next()函数使用方法介绍

#使用列表进行迭代
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

二、next()函数产生的StopIteration异常

#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

三、利用next()函数优化代码

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

四、next()函数在生成器中的应用

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

五、结论

本文固定链接:https://6yhj.com/leku-p-5027.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 百度统计