Search code examples
pythonlistsplitenumerate

Best way to split this list into smaller lists?


I've been trying to wrap my head around the best way to split this list of numbers up that are ordered but broken up in sections. Ex:

data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 29, 30, 31, 32, 33, 35, 36, 44, 45, 46, 47]

I'd like the output to be this..

sliced_data = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],[29, 30, 31, 32, 33],[35, 36],[44, 45, 46, 47]]

I've been trying a while look until it's empty but that isn't working too well..

Edit:

for each_half_hour in half_hour_blocks:
    if next_number != each_half_hour:
        skippers.append(half_hour_blocks[:next_number])
        del half_hour_blocks[:next_number]

    next_number = each_half_hour + 1

Solution

  • I don't see why a while-loop wouldn't work here, unless you're going for something more efficient or succinct.

    Something like:

    slice = [data.pop(0)]
    sliced_data = []
    while data:
        if data[0] == slice[-1] + 1:
            slice.append(data.pop(0))
        else:
            sliced_data.append(slice)
            slice = [data.pop(0)]
    sliced_data.append(slice)