Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
37 lines (29 loc) · 789 Bytes

File metadata and controls

37 lines (29 loc) · 789 Bytes
Copy raw file
Download raw file
Edit and raw actions
@author jackzhenguo
@desc
@tag
@version 
@date 2020/02/06

139 定制递减迭代器

#编写一个迭代器,通过循环语句,实现对某个正整数的依次递减1,直到0.
class Descend(Iterator):
    def __init__(self,N):
        self.N=N
        self.a=0
    def __iter__(self):
        return self 
    def __next__(self):
        while self.a<self.N:
            self.N-=1
            return self.N
        raise StopIteration
    
descend_iter=Descend(10)
print(list(descend_iter))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

核心要点:

1 __nex__ 名字不能变,实现定制的迭代逻辑

2 raise StopIteration:通过 raise 中断程序,必须这样写

[上一个例子](138.md) [下一个例子](140.md)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.