Split Integer List in Python
Question: I have a list of integers. I want to split the main list into multiple sub
lists of non-zero integers.

Example:

    
    
    main_lists = [0,0,0,0,0,0,123,432,5,54,0,654,645,34,23,12,0,0,0,0,0,0,123,1,312,312,132,3,123,0,0,0,0,0,0,0]
    
    output = 
    
    [123,432,5,54,0,654,645,34,23,12]
    [123,1,312,312,132,3,123]
    

Condition is, If one or two (less than < 5) zero is found in between two non
zero values, then it should include those zeros int out put lists. If more
that 5 consecutive zero is found then it should split the list from that
position.

    
    
    main_lists = [0,0,0,0,0,0,123,432,5,54,0,654,645,34,23,12,0,0,0,0,0,0,123,1,312,312,132,3,123,0,0,0,0,0,0,0]
    zero_count = 0
    non_zero_temp = []
    for i in main_lists:
        if i == 0:
            zero_count = zero_count + 1
        else:
            if zero_count < 5:
                non_zero_temp.append(i)
                zero_count = 0
    

Thanks in Advance,


Answer: 
    from itertools import groupby
    
    main_lists = [
        0,0,0,0,0,0,123,432,5,54,0,654,645,34,23,12,0,
        0,0,0,0,0,123,1,312,312,132,3,123,0,0,0,0,0,0,0
    ]
    
    # group numbers into contiguous lists (by 0 or not-0)
    is_zero = lambda n: not n
    groups = (list(nums) for zero,nums in groupby(main_lists, key=is_zero))
    
    # group lists into contiguous chunks (by to-keep or to-discard)
    is_keeper = lambda lst: bool(lst[0]) or len(lst) < 5
    chunks = (chunk for keep,chunk in groupby(grouped, key=is_keeper) if keep)
    
    # reassemble chunks
    final = [[i for lst in chunk for i in lst] for chunk in chunks]
    

results in

    
    
    [[123, 432, 5, 54, 0, 654, 645, 34, 23, 12], [123, 1, 312, 312, 132, 3, 123]]
    

