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

2024-05-15 21:42:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份清单:

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

你能帮我纠正一下吗


Tags: inforsizeifs3resvalsteps
2条回答

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

你有一个off-by-one error。更改以下行:

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

相关问题 更多 >