将Python列表拆分为匹配列表项分隔符上的列表列表的正确方法

时间:2016-09-09 19:19:19

标签: python

list = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']

def chunk(list, delim):
    ct = list.count(delim)
    chunks = [[]] * (ct+1)
    for iter in range(ct):
        idx = list.index(delim)
        chunks[iter] = list[:idx]
        list = list[idx+1:]
    chunks[ct] = list
    return chunks

print chunk(list, '')

产地:

[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

这就是我想要的,但我觉得这是实现这一目标的'c'方式。我应该知道更多的pythonistic构造吗?

4 个答案:

答案 0 :(得分:3)

这是一种方法using itertools.groupby

[list(v) for k, v in groupby(l, key=lambda x: x!= '') if k]

演示:

>>> from itertools import groupby
>>> l = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']
>>> ch = [list(v) for k, v in groupby(l, key=lambda x: x!= '') if k]
>>> ch
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

答案 1 :(得分:1)

关注Python中列表的可迭代性:

list = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']

def chunk(list, delim):
    aggregate_list = []
    current_list = []

    for item in list: 
      if item == delim:
        aggregate_list.append(current_list)
        current_list = []; 

        # You could also do checking here if delim is starting 
        #  index or ending index and act accordingly 
      else:
        current_list.append(item)

    return aggregate_list

print chunk(list, '')

答案 2 :(得分:1)

整齐的单行:

L = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']
new_l = [x.split("_") for x in "_".join(L).split("__")]

答案 3 :(得分:-1)

lists = ['a','b','c','','d','e','f','','g','h','i']
new_list = [[]]
delim = ''
for i in range(len(lists)):
    if lists[i] == delim:
        new_list.append([])
    else:
        new_list[-1].append(lists[i])

new_list
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]