繁体   English   中英

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

[英]Split list into lists by particular value

我有一个清单:

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

我想在下一个 S1 之前拆分:

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

我的代码是:

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

它将列表拆分为:

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

你能帮忙纠正一下吗!

您可以使用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']]

你有一个逐一错误 更改以下行:

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

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

结果应该是:

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