【问题标题】:split a list to several nested lists based on "2 consecutive" entries根据“2 个连续”条目将列表拆分为多个嵌套列表
【发布时间】:2019-10-12 01:28:55
【问题描述】:

我的问题在 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"]]

请帮忙。

【问题讨论】:

    标签: python list


    【解决方案1】:

    危险:不要使用内置函数作为变量名。 list是python的内置函数。

    试试这个,

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

    【讨论】:

      【解决方案2】:

      您可以分段执行此操作。首先,找到'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']
      

      【讨论】:

      猜你喜欢
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 2012-10-20
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      相关资源
      最近更新 更多