Python Cookbook学习记录 ch4_6/7_2013/11/2

4.6 展开一个嵌套的序列

使用了递归生成器,生成器(yield)这个东东的左右是每次产生多个值,函数就被冻结,函数停在那点等待激活,被激活后就从停止的那点开始执行

生成器这个东东感觉是只可意会不可言传呀。

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

4.7 在行列表中完成对列的删除和排序

使用列表推导式:

>>> listOfRows = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
>>> newlist = [[row[0],row[1],row[3]] for row in listOfRows]
>>> print newlist
[[1, 2, 4], [5, 6, 8], [9, 10, 12]]

嵌套的列表推导式:

>>> listOfRows = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
>>> newlist = [[row[index] for index in (0,1,3)] for row in listOfRows]
>>> print newlist
[[1, 2, 4], [5, 6, 8], [9, 10, 12]]

 

posted on 2013-11-02 22:15  七海之风  阅读(159)  评论(0)    收藏  举报

导航