如何实现将列表l1中的字典项两两分组并关联至列表l2的条目生成结构化结果
解决方案
要实现这个分组关联操作,核心思路是先把l1按每2个元素拆分成分组,再将每个分组对应挂载到l2的字典项中。下面分享两种实用的实现方式:
方法一:直观循环切片法
这是最容易理解的方式,先拆分l1,再逐个关联到l2的元素上:
l1 = [{'_id': 0, 'type': 'int', 'name': 'one', 'des': 1}, {'_id': 1, 'type': 'int', 'name': 'two', 'des': 2}, {'_id': 2, 'type': 'int', 'name': 'one', 'des': 1}, {'_id': 3, 'type': 'int', 'name': 'five', 'des': 5}] l2 = [{'g_id': 0, 'type': 'group1', 'name': 'first'}, {'g_id': 1, 'type': 'group2', 'name': 'second'}] # 把l1按每2个元素为一组拆分 l1_split_groups = [l1[i:i+2] for i in range(0, len(l1), 2)] group_result = [] # 遍历l2和拆分后的分组,给每个l2元素添加group字段 for l2_item, sub_group in zip(l2, l1_split_groups): # 用copy()创建副本,避免修改原l2的字典 new_item = l2_item.copy() new_item['group'] = sub_group group_result.append(new_item) print(group_result)
运行后就能得到你需要的group_result结构。
方法二:列表推导式简化版
如果想让代码更简洁,可以用字典解包+列表推导式一步完成:
l1 = [{'_id': 0, 'type': 'int', 'name': 'one', 'des': 1}, {'_id': 1, 'type': 'int', 'name': 'two', 'des': 2}, {'_id': 2, 'type': 'int', 'name': 'one', 'des': 1}, {'_id': 3, 'type': 'int', 'name': 'five', 'des': 5}] l2 = [{'g_id': 0, 'type': 'group1', 'name': 'first'}, {'g_id': 1, 'type': 'group2', 'name': 'second'}] l1_split_groups = [l1[i:i+2] for i in range(0, len(l1), 2)] # 用字典解包生成新字典,同时添加group字段 group_result = [{**item, 'group': sub_group} for item, sub_group in zip(l2, l1_split_groups)] print(group_result)
注意事项
- 要确保
l1的元素总数是l2长度的2倍,否则zip会以较短的列表长度为准,多余的元素会被忽略。如果需要处理长度不匹配的场景,可以额外加判断逻辑。 - 操作时尽量创建字典副本(比如
copy()或字典解包),避免不小心修改原l2里的元素。
内容的提问来源于stack exchange,提问作者I'm not a cat
相关产品推荐
相关产品推荐

