每隔['

编程入门 行业动态 更新时间:2024-10-27 08:28:02
每隔['-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']]]

更多推荐

本文发布于:2023-08-04 09:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1412399.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:每隔

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!