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

如何按Role键均匀分布字典列表 保留全部字段完整信息

实现方案

核心思路

你参考的均匀打散算法核心逻辑无需修改,仅需要将分组环节的存储对象从单独的角色值改为完整的字典条目,就可以保留所有字段:

  1. 按Role: Name字段对所有字典条目分组,同一角色的所有完整字典存入同一个列表
  2. 将所有角色分组按组内元素数量从多到少排序,避免数量最多的角色最后扎堆出现
  3. 循环遍历所有非空分组,依次从每个分组头部取出1个条目加入结果列表,直到所有分组为空

Python 代码实现

from collections import defaultdict

def uniform_shuffle_by_role(items):
    # 按角色分组,存储完整字典
    role_groups = defaultdict(list)
    for item in items:
        role_groups[item['Role: Name']].append(item)
    # 按组长度倒序排序,优先处理数量多的角色
    sorted_groups = sorted(role_groups.values(), key=lambda x: len(x), reverse=True)
    result = []
    # 循环取每个组的元素
    while sorted_groups:
        new_groups = []
        for group in sorted_groups:
            result.append(group.pop(0))
            # 组内还有元素的留存到下一轮
            if group:
                new_groups.append(group)
        sorted_groups = new_groups
    return result

# 输入示例
input_items = [{'User ID': '111',
  'Full Name': 'name a',
  'Role: Name': 'role a'},
 {'User ID': '222',
  'Full Name': 'name b',
  'Role: Name': 'role a'},
 {'User ID': '232',
  'Full Name': 'name c',
  'Role: Name': 'role b'},
 {'User ID': '223',
  'Full Name': 'name d',
  'Role: Name': 'role d'},
 {'User ID': '444',
  'Full Name': 'name e',
  'Role: Name': 'role d'}]

print(uniform_shuffle_by_role(input_items))

运行效果说明

针对你的输入示例,输出结果的角色顺序为['role a', 'role d', 'role b', 'role a', 'role d'],无相同角色相邻,且所有条目的User ID、Full Name字段完全保留。

注意事项

如果某一个角色的条目数量超过总条目数的一半+1,数学上无法避免出现相同角色相邻的情况,该场景下算法会尽可能减少相邻次数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:15:01