BZ易风

导航

 

1,for循环

 1 nums = list()
 2 
 3 a = 0
 4 b = 1
 5 i = 0
 6 
 7 while i<10:
 8     nums.append(a)
 9     a,b = b,a+b
10     i += 1
11 
12 for num in nums:
13     print(num)

除了for循环能接受可迭代对象,list、tuple等也能接收

1 a = (11,22,33)
2 # list() 不是简单的类型转换 是迭代的方式在a里面取值,重新生成列表 然后append()到列表中
3 #用tuple()转换的时候也一样用到迭代器
4 b = list(a)
5 print(b)

 

2.class

 1 class Feibonacci():
 2     def __init__(self,all_num):
 3         self.all_num = all_num
 4         self.a = 0
 5         self.b = 1
 6         self.current_num = 0
 7 
 8     def __iter__(self):
 9         return self
10 
11 
12     def __next__(self):
13         if self.current_num < self.all_num:
14             ret = self.a    # ? 能理解,但想不到用这种方法
15             self.a,self.b = self.b,self.a+self.b
16             self.current_num += 1
17             return ret
18         else:
19             raise StopIteration
20 
21 febo = Feibonacci(10)
22 
23 for num in febo:
24     print(num)

 

 

3.我能理解的class迭代器方式

 1 class Feibonacci():
 2     def __init__(self,all_num):
 3         self.all_num = all_num
 4         self.a = 0
 5         self.b = 1
 6         self.nums = list()
 7         self.current_num = 0
 8 
 9     def __iter__(self):
10         return self
11 
12 
13     def __next__(self):
14         if self.current_num < self.all_num:
15             self.nums.append(self.a)
16             self.a,self.b = self.b,self.a+self.b
17             ret = self.nums[self.current_num]
18             self.current_num += 1
19             return ret
20         else:
21             raise StopIteration
22 
23 febo = Feibonacci(10)
24 
25 for num in febo:
26     print(num)

 

posted on 2019-08-22 10:00  BZ易风  阅读(279)  评论(0编辑  收藏  举报