Python 迭代器 next 方法
Python iterator next method
Zen of Python 状态:
There should be one-- and preferably only one --obvious way to do it.
现在,给出以下内容:
nums = [2, 3, 4]
it = iter(nums)
it.__next__()
next(it)
最后两个语句有什么区别?他们都 return 迭代器中的下一个项目而不改变迭代器对象。我看到 .__next__()
可用于创建迭代器对象。这是唯一的区别吗?
next()
用于获取序列中的下一项或 StopIteration
异常(如果它位于末尾)。
next()
通过调用 class.
中定义的 __next__()
方法来做到这一点
一个例子
class my_list():
def __init__(self):
self.data = [1, 2, 3, 4, 5, 6]
self.pointer = 0
def __next__(self):
if self.pointer >= len(self.data):
self.pointer = 0
raise StopIteration # to stop the iteration
item = self.data[self.pointer]
self.pointer += 1
return item
my_list_obj = my_list()
print(next(my_list_obj)) # use next() function to call __next__()
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj, "empty")) # to print default value at the end
给出输出
1
2
3
4
5
6
empty
.__next__
是用户定义到return下一个对象
next()
是 .__next__
的方法包装器
与 +
运算符相同,调用 __add__
Zen of Python 状态:
There should be one-- and preferably only one --obvious way to do it.
现在,给出以下内容:
nums = [2, 3, 4]
it = iter(nums)
it.__next__()
next(it)
最后两个语句有什么区别?他们都 return 迭代器中的下一个项目而不改变迭代器对象。我看到 .__next__()
可用于创建迭代器对象。这是唯一的区别吗?
next()
用于获取序列中的下一项或 StopIteration
异常(如果它位于末尾)。
next()
通过调用 class.
__next__()
方法来做到这一点
一个例子
class my_list():
def __init__(self):
self.data = [1, 2, 3, 4, 5, 6]
self.pointer = 0
def __next__(self):
if self.pointer >= len(self.data):
self.pointer = 0
raise StopIteration # to stop the iteration
item = self.data[self.pointer]
self.pointer += 1
return item
my_list_obj = my_list()
print(next(my_list_obj)) # use next() function to call __next__()
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj))
print(next(my_list_obj, "empty")) # to print default value at the end
给出输出
1
2
3
4
5
6
empty
.__next__
是用户定义到return下一个对象
next()
是 .__next__
与 +
运算符相同,调用 __add__