Python 根据子列表中的第一个元素将列表拆分为子列表

Python Split list into sublists based on the first element in the sublists

我想拆分如下所示的列表:

list = [5, a, b, c, d, e, 2, a, b, 4, a ,b ,c ,d , ...]

进入这个:

list  = [ [5, a, b, c, d, e], [2, a, b] , [4, a ,b ,c ,d] ...]

第一个 element/number 是可变的,因此没有模式可以将它分成偶数块。 块的大小或长度应基于块的第一个元素。 此外,字母只是占位符,使示例更具可读性,实际上字母是浮点数和数字。

所以大名单真的是这样的:

list = [5, 7, 3.2, 3.1, 4.6, 3, 2, 5.1, 7.1, 4, 5.12 ,3.4 ,4.8 ,12.1 , ...]

你可以试试这个:

l = [5, 'a', 'b', 'c', 'd', 'e', 2, 'a', 'b', 4, 'a' ,'b' ,'c' ,'d']

pos = [(index, i) for index, i in enumerate(l) if type(i)==int]
l = [l[p[0]:p[0]+p[1]+1] for p in pos]
print(l)

输出:

[[5, 'a', 'b', 'c', 'd', 'e'], [2, 'a', 'b'], [4, 'a', 'b', 'c', 'd']]

简单的方法,读取每个块长度 n 并包括接下来的 n 个值:

it = iter(l)
[[n, *islice(it, n)] for n in it]

Python 2 版本:

it = iter(l)
[[n] + list(islice(it, n)) for n in it]

或没有islice:

it = iter(l)
[[n] + [next(it) for _ in range(n)] for n in it]

演示:

>>> from itertools import islice
>>> l = [5, 'a', 'b', 'c', 'd', 'e', 2, 'f', 'g', 4, 'h' ,'i' ,'j' ,'k']
>>> it = iter(l)
>>> [[n, *islice(it, n)] for n in it]
[[5, 'a', 'b', 'c', 'd', 'e'], [2, 'f', 'g'], [4, 'h', 'i', 'j', 'k']]

也可以尝试像这样简单的事情:

l = [5, 'a', 'b', 'c', 'd', 'e', 2, 'f', 'g', 4, 'h' ,'i' ,'j' ,'k']

numbers = [i for i, e in enumerate(l) if isinstance(e, int)]

result = [l[s:e] for s, e in zip(numbers[:-1], numbers[1:])] + [l[numbers[-1]:]]

print(result)
# [[5, 'a', 'b', 'c', 'd', 'e'], [2, 'f', 'g'], [4, 'h', 'i', 'j', 'k']]