程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python 中的 next() 函数:从迭代器读取数据

hfteth 2025-01-15 13:36:46 技术文章 12 ℃

Python next() 函数将迭代器作为参数,每次调用 next() 时,它都会返回迭代器中的下一项,直到没有任何剩余项。如果继续访问会引发 StopIterarion 异常。

在本教程中,你将了解在什么情况下可以使用 next() 函数。

next() 函数

next() 返回迭代器的下一个项目,一般和生成迭代器的 iter() 函数一起使用。

「语法格式:」

next(iterable[, default])

「参数说明:」

iterable -- 可迭代对象

default -- 可选,用于设置在没有下一个项目时返回该默认值,如果不设置,又没有下一个项目则会触发 StopIteration 异常。

「返回值」

返回迭代器的下一个项目。

>>> n = [1, 2, 3]
>>> m = iter(n)
>>> next(m)
1
>>> next(m)
2
>>> next(m)
3
>>> next(m)
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
StopIteration

如果我们多次调用 next() 函数,直到迭代器没有任何剩余项,就会返回 StopIteration 异常。

如果你不希望 Python 在迭代结束时引发 StopIteration 异常,可以将设置可选的 default 参数传递给 next() 函数。

>>> n = [1, 2, 3]
>>> m = iter(n)
>>> next(m, "迭代结束")
1
>>> next(m, "迭代结束")
2
>>> next(m, "迭代结束")
3
>>> next(m, "迭代结束")
'迭代结束'

next() 与 __next__()

Python 中一些对象具有一个名为 __next__() 的方法,__next__() 和 next() 有什么区别吗?

当调用 next() 函数时,其实是调用了迭代器对象的 __next__() 方法。我们可以直接调用迭代器的 __next__() 方法并返回相同的结果。

>>> n = [1, 2, 3]
>>> m = iter(n)
>>> m.__next__()
1
>>> m.__next__()
2
>>> m.__next__()
3
>>> m.__next__()
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
StopIteration

next() 与生成器表达式

next() 不能直接迭代可迭代的序列,需要与 iter() 函数配合使用。除此之外, next() 还可以与生成器表达式一起使用。

>>> n = [1, 2, 3]
>>> m = (2*i for i in n) 
>>> next(m)
2
>>> next(m)
4
>>> next(m)
6
>>> next(m)
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
StopIteration

for 循环迭代与 next() 性能

我们经常使用 for 循环迭代可迭代对象,与 next() 相比,哪一种具有更好的性能?

让我们创建一个包含 10000 个项目的列表,测试 for 循环迭代与 next() 性能。

「for 循环」

import datetime 
n = list(range(1,10001))
start = datetime.datetime.now() 
for i in n:
    print(i)
end = datetime.datetime.now()
print(f"迭代时间:{end - start}") 

迭代时间:0:00:34.785542

「next()」

import datetime 
n = iter(range(1,10001))
start = datetime.datetime.now() 
while True:
    m = next(n, None) 
    if m:
        print(m)
    else:
        break
end = datetime.datetime.now()
print(f"迭代时间:{end - start}") 

迭代时间:0:00:37.721296

我们发现 for 循环迭代比 next() 函数更快,也可能受 while 循环和 if 语句的影响。

?

文章创作不易,如果您喜欢这篇文章,请关注、点赞并分享给朋友。如有意见和建议,请在评论中反馈!

?

Tags:

最近发表
标签列表