每隔['-1']拆分嵌套列表(Splitting Nested List at every ['-1'])
如果我有这样的嵌套列表:
[['01'], ['02'], ['-1'], ['03'], ['04']]有没有办法在每个['-1']分割这个嵌套列表?
所以它看起来像这样:
[[['01'], ['02']], [['03'], ['04']]]任何形式的帮助将不胜感激:)
If I have a nested list like this:
[['01'], ['02'], ['-1'], ['03'], ['04']]Is there a way I split this nested list at every ['-1']?
So that it looks like this:
[[['01'], ['02']], [['03'], ['04']]]Any sort of help would be appreciated :)
最满意答案
尝试这个,
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']]]Try this,
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']]]更多推荐
发布评论