Python 在每[';-1';]处拆分嵌套列表

Python 在每[';-1';]处拆分嵌套列表,python,list,Python,List,如果我有这样一个嵌套列表: [['01'], ['02'], ['-1'], ['03'], ['04']] [[['01'], ['02']], [['03'], ['04']]] 是否有办法在每个['-1']处拆分此嵌套列表 所以它看起来像这样: [['01'], ['02'], ['-1'], ['03'], ['04']] [[['01'], ['02']], [['03'], ['04']]] 任何形式的帮助都将不胜感激:)试试这个 lists = [['01'], ['02'

如果我有这样一个嵌套列表:

[['01'], ['02'], ['-1'], ['03'], ['04']]
[[['01'], ['02']], [['03'], ['04']]]
是否有办法在每个
['-1']
处拆分此嵌套列表

所以它看起来像这样:

[['01'], ['02'], ['-1'], ['03'], ['04']]
[[['01'], ['02']], [['03'], ['04']]]
任何形式的帮助都将不胜感激:)

试试这个

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']]]
list=['01']、['02']、['-1']、['03']、['04']、['-1']、['05']、['-1']]
结果=列表()
上一个idx=0
对于idx,枚举中的l(列表):
如果l==['-1']:
results.append(列出[prev_idx:idx])
上一个idx=idx+1
如果上一个idx试试这个

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']]]
list=['01']、['02']、['-1']、['03']、['04']、['-1']、['05']、['-1']]
结果=列表()
上一个idx=0
对于idx,枚举中的l(列表):
如果l==['-1']:
results.append(列出[prev_idx:idx])
上一个idx=idx+1

如果prev_idx一个好的老式循环应该做到这一点:

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

一个好的老式循环应该可以做到这一点:

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']]]
似乎是groupby的一个用例

似乎是groupby的一个用例

您可以使用在每次出现分割值时进行分组(此处
['-1']
如果不是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']
如果不是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]