简体   繁体   English

按特定值将列表拆分为列表

[英]Split list into lists by particular value

I have a list:我有一个清单:

['S1', 'S2', 'S6', 'S1', 'S2', 'S3', 'S4', 'S5', 'S1', 'S2', 'S5', 'S1',
 'S2', 'S4', 'S5', 'S1', 'S2', 'S4', 'S5', 'S1', 'S2', 'S3', 'S6']

and I want to split by next S1:我想在下一个 S1 之前拆分:

[['S1', 'S2', 'S6']['S1', 'S2', 'S3', 'S4', 'S5'],['S1', 'S2', 'S4', 'S5]...]

My code is:我的代码是:

size = len(steps)
idx_list = [idx + 1 for idx, val in
            enumerate(steps) if val == 'S1'] 


res = [steps[i: j] for i, j in
        zip([0] + idx_list, idx_list + 
        ([size] if idx_list[-1] != size else []))] 

print("The list after splitting by a value : " + str(res))

It splits the list as:它将列表拆分为:

[['S1'], ['S2', 'S6', 'S1'], ['S2', 'S3', 'S4', 'S5', 'S1'], 
 ['S2', 'S5', 'S1'], ['S2', 'S4', 'S5', 'S1'], ['S2', 'S4', 'S5', 'S1']..

Can you please help to rectify it!你能帮忙纠正一下吗!

You can use itertools.groupby :您可以使用itertools.groupby

from itertools import groupby

lst = ['S1', 'S2', 'S6', 'S1', 'S2', 'S3', 'S4', 'S5', 'S1', 'S2', 'S5', 'S1', 'S2', 'S4', 'S5', 'S1', 'S2', 'S4', 'S5', 'S1', 'S2', 'S3', 'S6']

splitby = 'S1'
res = [[splitby] + list(g) for k, g in groupby(lst, key=lambda x: x != splitby) if k]

# [['S1', 'S2', 'S6'], ['S1', 'S2', 'S3', 'S4', 'S5'], ['S1', 'S2', 'S5'], ['S1', 'S2', 'S4', 'S5'], ['S1', 'S2', 'S4', 'S5'], ['S1', 'S2', 'S3', 'S6']]

You have an off-by-one error .你有一个逐一错误 Change the following line:更改以下行:

idx_list = [idx + 1 for idx, val in
            enumerate(steps) if val == 'S1'] 

to

idx_list = [idx for idx, val in
            enumerate(steps) if val == 'S1' and idx > 0] 

The result should then be:结果应该是:

[['S1', 'S2', 'S6'], ['S1', 'S2', 'S3', 'S4', 'S5'], 
 ['S1', 'S2', 'S5'], ['S1', 'S2', 'S4', 'S5'], 
 ['S1', 'S2', 'S4', 'S5'], ['S1', 'S2', 'S3', 'S6']]

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

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