将此列表拆分为较小列表的最佳方法是什么?

时间:2014-03-09 00:45:57

标签: python list split enumerate

我一直试图绕过最好的方法来分割这些已经订购的数字列表但是分成几部分。例如:

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]

我希望输出是这个..

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]]

我一直在尝试,直到它空了但是效果不好......

编辑:

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

2 个答案:

答案 0 :(得分:7)

>>> 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]
>>> from itertools import groupby, count
>>> [list(g) for k,g in groupby(data, key=lambda i, c=count():i-next(c))]
[[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]]

答案 1 :(得分:1)

我不明白为什么while-loop在这里不起作用,除非你想要更高效或更简洁的东西。

类似的东西:

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)