Python生成器实践

Sample-1

 1 def my_func():
 2     for i in range(1,4):
 3         yield i
 4 
 5 print list(my_func())
 6 
 7 print my_func()
 8 
 9 for element in my_func():
10     print element

Output

1 [1, 2, 3]
2 <generator object my_func at 0xbd87d0>
3 1
4 2
5 3

在遍历其中的元素时,可以直接用 element in my_func() 当然 element in list(my_func()) 也可以


Sample-2

1 def my_func(num, state=()):
2     if len(state) == num-1:
3         yield (len(state),)
4     else:
5         for result in my_func(num, state+(1,)):
6             yield (len(state),)+result
7 
8 print list(my_func(8))

Output

1 [(0, 1, 2, 3, 4, 5, 6, 7)]
原文地址:https://www.cnblogs.com/mess4u/p/2736855.html