简体   繁体   English

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

[英]Python Split list into sublists based on the first element in the sublists

I want to split a list that looks something like this: 我想拆分一个看起来像这样的列表:

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

into this: 到这个:

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

The first element/number is variable, so no pattern to split it in even chunks. 第一个元素/数字是可变的,因此没有可将其分成偶数块的模式。 The chunks size or length should be based on that first element of the chunk. 块的大小或长度应基于块的第一个元素。 Also the alphabetic letters are just placeholders to make the example more readable, in reality the alphabetic letters are floats and numbers. 同样,字母只是用于使示例更易读的占位符,实际上字母是浮点数和数字。

So the big list really looks something like this: 因此,大清单确实看起来像这样:

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

Simple way, read each chunk length n and include the next n values: 一种简单的方法,读取每个块长度n并包括接下来的n个值:

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

Python 2 version: Python 2版本:

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

Or without islice : 或者没有islice

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

Demo: 演示:

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

You can try this one: 您可以尝试以下一种方法:

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)

Output: 输出:

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

Could also trying something simple like this: 也可以尝试这样的简单操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM