代码如下:
#encoding=utf-8 print '中国' #展开嵌套序列 序列的子序列进行展开 print '----递归' def list_or_tuple(x): return isinstance(x,(list,tuple)) def flatten(sequence, to_expand=list_or_tuple): for item in sequence: if to_expand(item): for subitem in flatten(item,to_expand): yield subitem else: yield item lista=[[1,2,[3,4,[5,6]]],7,8,(9,10,(11,12))] for idx,item in enumerate(flatten(lista)): print idx,item print '----非递归 链表' def flatten2(sequence, to_expand=list_or_tuple): iterators = [ iter(sequence) ] while iterators: for item in iterators[-1]: if to_expand(item): iterators.append(iter(item)) break else: yield item else: iterators.pop( ) for idx,item in enumerate(flatten2(lista)): print idx,item打印结果如下:
中国
----递归
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
11 12
----非递归 链表
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
11 12