用定界符将列表分成子列表

时间:2018-10-23 12:20:59

标签: python-3.x list while-loop

我有一个列表列表:

[[0, 0], [0, 0], [0, 0], [0, 1, 0], [0, 0]]

我想将其拆分为列表[0,1,0]之前的内容和之后的内容:

[[0, 0], [0, 0], [0, 0]], [[0, 0]]

如果我有一个列表:

[[0, 0], [0, 0], [0, 0], [0, 1, 0], [0, 0], [0, 1, 0], [0, 0]]

我想将其分成这样的列表:

[[0, 0], [0, 0], [0, 0]], [[0, 0]], [[0, 0]]

我确实受制于while循环,似乎并没有在正确的位置重置临时列表:

def count_normal_jumps(jumps):
    _temp1 = []
    normal_jumps = []
    jump_index = 0
    while jump_index <= len(jumps) - 1:
        if jumps[jump_index] == [0,0]:
            _temp1.append(jumps[jump_index])
        else:
            normal_jumps.append(_temp1)
            _temp1[:] = []
        jump_index += 1
    return normal_jumps

为什么这不起作用,有没有更好的方法?

2 个答案:

答案 0 :(得分:2)

您可以使用for循环将列表中的子列表追加到列表列表中的最后一个子列表,并在输入子列表等于{{1 }}:

[0, 1, 0]

或者您可以使用def split(lst): output = [[]] for l in lst: if l == [0, 1, 0]: output.append([]) else: output[-1].append(l) return output

itertools.groupby

这样:

from itertools import groupby
def split(lst):
    return [list(g) for k, g in groupby(lst, key=[0, 1, 0].__ne__) if k]

输出:

print(split([[0, 0], [0, 0], [0, 0], [0, 1, 0], [0, 0]]))
print(split([[0, 0], [0, 0], [0, 0], [0, 1, 0], [0, 0], [0, 1, 0], [0, 0]]))

答案 1 :(得分:0)

您可以执行以下操作:

myList = [[0, 0], [0, 0], [0, 0], [0, 1, 0], [0, 0]]

toMatch = [0, 1, 0]
allMatches = []

currentMatches = []
for lst in myList:
    if lst == toMatch:
        allMatches.append(currentMatches)
        currentMatches = []
    else:
        currentMatches.append(lst)

#push leftovers when end is reached
if currentMatches:
    allMatches.append(currentMatches)

print(allMatches)
相关问题