具体解释了怎么用迭代,怎样用迭代,怎样转换成迭代,可以看看
- 列表,字典,元组,字符串,集合可以使用迭代
- 自定义类中可以定义iter方法,来使用迭代
- iter方法意为可以迭代
- iterator意为定义迭代的对象(既有__iter__方法,也有__next__方法)
(一)
复制代码
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
47from collections.abc import Iterable from collections.abc import Iterator import time class Person(object): def __init__(self): self.names = list() self.current_num = 0 def add_person(self,name): self.names.append(name) def __iter__(self): #pass return PersonsIterator(self) class PersonsIterator(object): def __init__(self,obj): self.obj = obj self.current_num = 0 def __iter__(self): pass def __next__(self): #pass #return 12345 if self.current_num < len(self.obj.names): ret = self.obj.names[self.current_num] self.current_num += 1 #return self.obj.names[self.current_num] return ret else: raise StopIteration p1 = Person() p1.add_person('张三') p1.add_person('李四') p1.add_person('王五') p_iter = iter(p1) while True: try: ret = next(p_iter) print(ret) except Exception: break
运行结果:
(二)
复制代码
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
52from collections.abc import Iterable from collections.abc import Iterator import time class Person(object): def __init__(self): self.names = list() self.current_num = 0 def add_person(self,name): self.names.append(name) def __iter__(self): #pass return PersonsIterator(self) class PersonsIterator(object): def __init__(self,obj): self.obj = obj self.current_num = 0 def __iter__(self): pass def __next__(self): #pass #return 12345 if self.current_num < len(self.obj.names): ret = self.obj.names[self.current_num] self.current_num += 1 #return self.obj.names[self.current_num] return ret else: raise StopIteration p1 = Person() p1.add_person('张三') p1.add_person('李四') p1.add_person('王五') print(isinstance(p1,Iterable)) #判断是否可以迭代 # iter()的作用是调用p1的iter()方法 # next()的作用是调用迭代器的next方法 p_Iterator = iter(p1) print(isinstance(p_Iterator,Iterator)) #判断是否为迭代器 for temp in p1: print(temp) time.sleep(1)
运行结果:
最后
以上就是柔弱煎饼最近收集整理的关于python中的iter迭代的全部内容,更多相关python中内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复