Movatterモバイル変換


[0]ホーム

URL:


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

Sign up
Appearance settings

Commit588f067

Browse files
committed
Iterators Tutorial
1 parent9e4da1f commit588f067

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
classSentence:
3+
4+
def__init__(self,sentence):
5+
self.sentence=sentence
6+
self.index=0
7+
self.words=self.sentence.split()
8+
9+
def__iter__(self):
10+
returnself
11+
12+
def__next__(self):
13+
ifself.index>=len(self.words):
14+
raiseStopIteration
15+
index=self.index
16+
self.index+=1
17+
returnself.words[index]
18+
19+
20+
defsentence(sentence):
21+
forwordinsentence.split():
22+
yieldword
23+
24+
25+
my_sentence=sentence('This is a test')
26+
27+
# for word in my_sentence:
28+
# print(word)
29+
30+
print(next(my_sentence))
31+
print(next(my_sentence))
32+
print(next(my_sentence))
33+
print(next(my_sentence))
34+
print(next(my_sentence))
35+
36+
37+
# This should have the following output:
38+
# This
39+
# is
40+
# a
41+
# test

‎Python/Iterators/iter-demo.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2+
classMyRange:
3+
4+
def__init__(self,start,end):
5+
self.value=start
6+
self.end=end
7+
8+
def__iter__(self):
9+
returnself
10+
11+
def__next__(self):
12+
ifself.value>=self.end:
13+
raiseStopIteration
14+
current=self.value
15+
self.value+=1
16+
returncurrent
17+
18+
19+
defmy_range(start):
20+
current=start
21+
whileTrue:
22+
yieldcurrent
23+
current+=1
24+
25+
26+
nums=my_range(1)
27+
28+
fornuminnums:
29+
print(num)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp