Creating a list within a list in Python

前端 未结 5 1273
挽巷
挽巷 2021-01-21 05:48

I have a list named values containing a series of numbers:

values = [0, 1, 2, 3, 4, 5, ... , 351, 0, 1, 2, 3, 4, 5, 6, ... , 750, 0, 1, 2, 3, 4, 5, ... , 559]
         


        
5条回答
  •  花落未央
    2021-01-21 06:46

    This should work:

    values = [0, 1, 2, 3, 4, 5, 351, 0, 1, 2, 3, 4, 5, 6, 750, 0, 1, 2, 3, 4, 5, 559]
    new_values = []
    
    split_at = 0  # split the list when this value is reached
    
    idx = -1
    for value in values:
        if value == split_at:
            idx += 1
            new_values.append([])
    
        new_values[idx].append(value)
    

    Output:

    [[0, 1, 2, 3, 4, 5, 351], [0, 1, 2, 3, 4, 5, 6, 750], [0, 1, 2, 3, 4, 5, 559]]
    

    It also handles edgecasses.

    My method is a bit faster than Chris_Rands's, but it's also a bit slower than Vasilis G's method:

    from itertools import groupby
    
    
    values = [
        0, 1, 2, 3, 4, 5, 351,
        0, 1, 2, 3, 4, 5, 6, 750,
        0, 1, 2, 3, 4, 5, 559,
    ]
    
    
    def method1():
        new_values = []
    
        idx = -1
        for value in values:
            if value == 0:
                idx += 1
                new_values.append([])
    
            new_values[idx].append(value)
    
        return new_values
    
    
    def method2():
        new_values = [[0] + list(g) for k, g in groupby(values, bool) if k]
        return new_values
    
    
    def method3():
        indices = [index for index, value in enumerate(values) if value == 0] + [len(values)]
        new_values = [values[indices[i]:indices[i + 1]] for i in range(len(indices) - 1)]
        return new_values
    

    >>> timeit.timeit(method1, number=100000)
    0.6725746986698414
    >>> timeit.timeit(method2, number=100000)
    0.8143814620314903
    >>> timeit.timeit(method3, number=100000)
    0.6596001360341748
    

提交回复
热议问题