python yield

描述:遍历数据,数据为数字或者由数字填充的列表

不使用生成器

1 data = [[1, 2], [3, 2], [5]]
2 
3 for lst in data:
4     for item in lst:
5         print item

使用生成器

1 data = [[1, 2], [3, 2], [5]]
2 
3 def flatten(nested):
4     for lst in nested:
5         for element in lst:
6             yield element
7 
8 for item in flatten(data):
9     print item

如果嵌套的层数不定

使用生成器

 1 data_1 = [1, 3]
 2 data_2 = [[3, 1], [4, 1]]
 3 data_3 = [1, 2]
 4 
 5 data = [data_1, data_2, data_3]
 6 
 7 def flatten(nested):
 8     try:
 9         for lst in nested:
10             for item in flatten(lst):
11                 yield item
12     except:
13         yield nested
14 
15 for item in flatten(data):
16    print item

 不使用生成器

 1 data_1 = [1, 3]
 2 data_2 = [[3, 1], [4, 1]]
 3 data_3 = [1, 2]
 4 
 5 data = [data_1, data_2, data_3]
 6 
 7 def foo(data):
 8     for item in data:
 9         if type(item) is type(1):
10             print item,
11         else:
12             foo(item)
13 
14 foo(data)

参考:《python基础教程》 人民邮电出版社

python yield,布布扣,bubuko.com

python yield

上一篇:c++第十三章 -(副本构造器)


下一篇:【c++】虚函数描写叙述符override