2011-03-02

    Python, Group a list into chunks in Python - [Python]

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
    http://webpeipei.blogbus.com/logs/107512519.html

     

    将元组中的数据分割为元组

    这方法很好用,非常适合目前项目使用,记下来(原文见 Groupe a list into chunks in Python

    def group_iter(iterator, n=2, strict=False):
        accumulator = []
        for item in iterator:
            accumulator.append(item)
            if len(accumulator) == n: # tested as fast as separate counter
                yield tuple(accumulator)
                accumulator = [] # tested faster than accumulator[:] = []
                # and tested as fast as re-using one list object
        if strict and len(accumulator) != 0:
            raise ValueError("Leftover values")

     

    lists = ('1','2','c','d','2','3','c','d','3','4','c','d')
    gtp =group_iter(lists,4) #conver list to 
    log=file('D:\\test.txt','a')
    for tp in gtp:
        print '\t'.join(tp)
        log.write('\t'.join(tp))
        log.write('\n')


    运行结果

     


    历史上的今天:

    Grub重建 2010-03-02

    收藏到:Del.icio.us




    引用地址: