小码哥的IT人生

Python next() 函数

Python基础 2022-06-06 14:35:05小码哥的IT人生shichen

Python next() 函数

实例

创建一个迭代器,并逐一打印项目:

mylist = iter(["apple", "banana", "cherry"])
x = next(mylist)
print(x)
x = next(mylist)
print(x)
x = next(mylist)
print(x)

完整实例:

mylist = iter(["apple", "banana", "cherry"])
x = next(mylist)
print(x)
x = next(mylist)
print(x)
x = next(mylist)
print(x)

定义和用法

next() 函数返回迭代器中的下一项。

您可以添加默认的返回值,以在迭代结束时返回。

语法

next(iterable, default)

参数值

参数 描述
iterable 必需。可迭代对象。
default 可选。在迭代结束时返回的默认值。

更多实例

示例代码:

当迭代结束时返回一个默认值:

mylist = iter(["apple", "banana", "cherry"])
x = next(mylist, "orange")
print(x)
x = next(mylist, "orange")
print(x)
x = next(mylist, "orange")
print(x)
x = next(mylist, "orange")
print(x)

完整实例:

mylist = iter(["apple", "banana", "cherry"])
x = next(mylist, "orange")
print(x)
x = next(mylist, "orange")
print(x)
x = next(mylist, "orange")
print(x)
x = next(mylist, "orange")
print(x)

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024