簡體   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