forked from yidao620c/python3-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_iter.py
More file actions
60 lines (48 loc) · 1.16 KB
/
custom_iter.py
File metadata and controls
60 lines (48 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc : 自定义迭代器
"""
from random import choice
__author__ = 'Xiong Neng'
# 随机序列迭代器
class RandomSeq(object):
def __init__(self, seq):
self.seq = seq
def __iter__(self):
return self
def next(self):
return choice(self.seq)
# 任意项的迭代器
class AnyIter(object):
def __init__(self, data, safe=False):
self.safe = safe
self.iter = iter(data)
def __iter__(self):
return self
def next(self, howmany=1):
retval = []
for eachItem in range(howmany):
try:
retval.append(self.iter.next())
except StopIteration:
if self.safe:
break
else:
raise
return retval
def main():
aa = AnyIter(range(10))
myiter = iter(aa) # 获取a的迭代器对象
print(type(myiter))
for j in range(1, 5):
print('%02d : %s' % (j, myiter.next(j)))
m = None
n = ''
k = ''
print(id(m))
print(id(n))
print(id(k))
if __name__ == '__main__':
main()