You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python字典列表以id=1为起始点拆分为多个子列表

实现代码

list_dict = [
 {'id': 1},
 {'item': 'apple'},
 {'id': 2},
 {'item': 'pear'},
 {'id': 1},
 {'item': 'peach'},
 {'id': 2},
 {'item': 'kiwi'},
 {'id': 3},
 {'item': 'banana'},
 {'id': 4},
 {'item': 'mango'},
 {'id': 1},
 {'item': 'watermelon'},
 {'id': 2},
 {'item': 'plum'},
 {'id': 3},
 {'item': 'grapes'}]

result = []
current_sub = []

for item in list_dict:
    # 遇到id为1的字典就开启新子列表
    if item == {'id': 1}:
        if current_sub:
            result.append(current_sub)
        current_sub = [item]
    else:
        current_sub.append(item)
# 追加最后一段子列表
if current_sub:
    result.append(current_sub)

补充说明

  • 上述代码运行后得到的result和你要求的输出完全匹配
  • 如果实际业务中id为1的字典可能包含其他键值对,可以将判断条件替换为if item.get('id') == 1,适配性更强

内容的提问来源于stack exchange,提问作者Kat9977

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 22:27:02