【问题标题】:Split a list in python with an element as the delimiter? [duplicate]用元素作为分隔符在python中拆分列表? [复制]
【发布时间】:2020-06-10 22:30:46
【问题描述】:

我想从包含许多重复元素的列表中创建子列表,即。

l = ['a', 'b', 'c', 'c', 'b', 'a', 'b', 'c', 'b', 'a']

无论'a' 从哪里开始,列表都应该被拆分。 (最好删除'a',但不是必须的)

这样:

l = [ ['b', 'c', 'c', 'b'], ['b', 'c', 'b'] ]

我尝试过new_list = [x.split('a')[-1] for x in l],但没有得到想要的“新列表”效果。

【问题讨论】:

标签: python python-3.x list split delimiter


【解决方案1】:

不包含分隔符

import itertools
lst =  ['a', 'b', 'c', 'c', 'b', 'a', 'b', 'c', 'b', 'a']
delimiter  = lst[0]

li=[list(value) for key,value in itertools.groupby(lst, lambda e: e == delimiter) if not key]

print(li)

说明:groupby函数会在每次key改变时创建一个新组

 Key     value
True     itertools._grouper object pointing to group 'a'
False    itertools._grouper object pointing to group 'b', 'c', 'c', 'b'
True     itertools._grouper object pointing to group 'a'
False    itertools._grouper object pointing to group 'b', 'c', 'b' 
True     itertools._grouper object pointing to group 'a'

在 if 条件下检查 key 是否为 false,返回 itertools._grouper 对象,然后将 itertool 对象 传递给列表。

【讨论】:

    【解决方案2】:

    为要拆分的每个元素创建一个计数器数组,然后以这种方式编写条件:

    l = ['a', 'b', 'c', 'c', 'b', 'a', 'b', 'c', 'b', 'a']
    counters = [0,0,0]                                #to count instances
    index = 0                                         #index of l
    startIndex = 0                                    #where to start split
    endIndex = 0                                      #where to end split
    splitLists = []                                   #container for splits
    for element in l:
        if element == 'a':                            #find 'a'
            counters[0] += 1                          #increase counter
            if counters[0] == 1:                      #if first instance
                startIndex = index + 1                      #start split after
        if counters[0] == 2:
            endIndex = index                         #if second instance
            splitList = l[startIndex:endIndex]           #end split here
            counters[0] = 1                              #make second starting location
            startIndex = index + 1
            splitLists.append(splitList)                 #append to main list of lists
        index += 1
    print(splitLists)
    

    所以基本上你是在列表中找到匹配模式的开始和结束索引。您可以使用这些来拆分列表,并将此列表附加到列表的主列表(二维列表)中。

    【讨论】:

      【解决方案3】:

      当你写作时,

      new_list = [x.split('a')[-1] for x in l]
      

      你实际上是在表演,

      result = []
      for elem in l:
         result.append(elem.split('a')[-1])
      

      也就是说,您将 l 中包含的每个字符串拆分到字母 'a' 上,并将每个字符串的最后一个元素收集到结果中。

      这是您正在寻找的机制的一种可能实现:

      def extract_parts(my_list, delim):
          # Locate the indices of all instances of ``delim`` in ``my_list``
          indices = [i for i, x in enumerate(my_list) if x == delim]
      
          # Collect each end-exclusive sublist bounded by each pair indices
          sublists = []
          for i in range(len(indices)-1):
              part = my_list[indices[i]+1:indices[i+1]]
              sublists.append(part)
          return sublists
      
      

      使用这个函数,我们有

      >>> l = ['a', 'b', 'c', 'c', 'b', 'a', 'b', 'c', 'b', 'a']
      >>> extract_parts(l, 'a') 
      [['b', 'c', 'c', 'b'], ['b', 'c', 'b']]
      

      【讨论】:

        【解决方案4】:

        您可以使用 zip 和枚举来执行此操作。创建一个用于分离的 id 列表,然后在这些点处将其拆分。

        size = len(l)
        id_list = [id + 1 for id, val in
                enumerate(test_list) if val == 'a']
        
        
        result = [l[i:j] for i, j in zip([0] + id_list, id_list +
            ([size] if id_list[-1] != size else []))]
        

        【讨论】:

        • 用全局变量遮蔽 buitlins(例如id)通常是个坏主意。另外,test_list 是什么?应该和l一样吗?
        • @Brian,是的,你是对的,我只是快速提出了一些问题,我很抱歉,从现在开始我会牢记这一点。
        • 即使在更正了上述错误命名的变量之后,这种方法也不会产生 OP 期望的输出。使用 OP 的示例输入产生 [['a'], ['b', 'c', 'c', 'b', 'a'], ['b', 'c', 'b', 'a']]
        • @Brian OP说不是必须的,所以我这样做了
        猜你喜欢
        • 2019-04-10
        • 2019-04-08
        • 2018-05-19
        • 2020-01-05
        • 2022-01-19
        • 1970-01-01
        • 2019-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多