每隔['-1']拆分嵌套列表

时间:2016-06-17 08:32:02

标签: python list

如果我有这样的嵌套列表:

[['01'], ['02'], ['-1'], ['03'], ['04']]

我有没有办法在每个['-1']分割这个嵌套列表?

所以它看起来像这样:

[[['01'], ['02']], [['03'], ['04']]]

任何形式的帮助将不胜感激:)

4 个答案:

答案 0 :(得分:2)

您可以使用itertools.groupby在每次出现拆分值时进行分组(此处为['-1'])。 if not k确保我们省略拆分值。

orig = [['01'], ['02'], ['-1'], ['03'], ['04']]
from itertools import groupby
n = [list(g) for k, g in groupby(orig, lambda x: x == ['-1']) if not k]

答案 1 :(得分:1)

试试这个,

lists = [['01'], ['02'], ['-1'], ['03'], ['04'], ['-1'], ['05'], ['-1']]

results = list()
prev_idx = 0
for idx, l in enumerate(lists):
    if l == ['-1']:
        results.append(lists[prev_idx:idx])
        prev_idx = idx+1

if prev_idx <= idx:     # the last group might be [] as shown in this case
    results.append(lists[prev_idx:])

print(results)
# Output
[[['01'], ['02']], [['03'], ['04']], [['05']]]

答案 2 :(得分:1)

似乎是 groupby

的用例
>>> from itertools import groupby
>>> l = [['01'], ['02'], ['-1'], ['03'], ['04'], ['-1'], ['05'], ['06']]    
>>> [list(g) for k,g in groupby(l, lambda x: x == ['-1']) if not k]
[[['01'], ['02']], [['03'], ['04']], [['05'], ['06']]]

itertools.groupby docs

答案 3 :(得分:0)

一个好的老式循环应该这样做:

l = [['01'], ['02'], ['-1'], ['03'], ['04']]

new = []

current = []  # Build a new list here
for i, item in enumerate(l):
    if item != ['-1']:
        current.append(item)
        if i == len(l) - 1:  # If the item is the last in the list
            new.append(current)
    else:
        new.append(current)
        current = []

>>>  [[['01'], ['02']], [['03'], ['04']]]