根据“ 2个连续”条目将列表拆分为几个嵌套列表

时间:2019-05-26 00:07:32

标签: python list

我的问题在 Python split for lists页。但是,我需要基于两个连续的组件(而不是一个组件)进行拆分。而代码是在Python中。 例如:

list = ["id","title","data","more data","id","title","data 2","more data 2","danger","id","title","date3","lll"]

我希望得到以下结果:

new_list = [["id","title","data","more data"],["id","title","data 2","more data 2","danger"],["id","title","date3","lll"]]

请帮助。

2 个答案:

答案 0 :(得分:0)

危险:请勿将内置函数用作变量名。 list是python中的内置功能。<​​/ p>

尝试一下

>>> list1 = ["id","title","data","more data","id","title","data 2","more data 2","danger","id","title","date3","lll"]
>>> new_list = []
>>> new_list_ = []
>>> for l in list1:
        if list1[0]==l:
            if new_list_:
                new_list.append(new_list_)
            new_list_ = []
        new_list_.append(l)
        if list1.index(l)==len(list1)-1:
            new_list.append(new_list_)

输出:

>>> new_list
[['id', 'title', 'data', 'more data'], ['id', 'title', 'data 2', 'more data 2', 'danger'], ['id', 'title', 'date3', 'lll']]
>>> 

答案 1 :(得分:0)

您可以分段进行此操作。首先,找到'id'的所有索引,其中下一项是'title'

lst = ["id","title","data","more data","id","title","data 2","more data 2","danger","id","title","date3","lll"]
lst_len = len(lst)
indexes = [i for i, v in enumerate(lst) if v=='id' and i+1 < lst_len and lst[i+1]=='title']

然后将它们成对迭代并适当地拆分。

import itertools

# from itertools recipes
def pairwise(iterable, fillvalue=None):
    a, b = iter(iterable), iter(iterable)
    next(b, None)
    return itertools.zip_longest(a, b, fillvalue=fillvalue)

result = [lst[i:j] for i,j in pairwise(indexes)]
>>> result
[['id', 'title', 'data', 'more data'], ['id', 'title', 'data 2', 'more data 2', 'danger'], ['id', 'title', 'date3', 'lll']]

您也可以使用成对迭代器来更快地找到索引。

indexes = [i for i, (a, b) in enumerate(pairwise(lst)) if a=='id' and b=='title']