• 2011-03-02

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

     

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

    这方法很好用,非常适合目前项目使用,记下来(原文见 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')


    运行结果