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

如何从父字典生成指定长度的循环滑动式叶节点字典列表

实现思路
  • Python 3.7及以上版本字典默认保留插入顺序,若使用更低版本需用collections.OrderedDict存储原字典,确保键值对顺序符合预期。
  • 先将原字典的键值对转换为列表,方便按索引定位取值。
  • 遍历每个起始索引,通过取模运算实现末尾循环衔接开头的逻辑,每次取连续n个键值对拼接为字典,加入结果列表即可。
代码实现
def generate_dict_list(d: dict, n: int) -> list[dict]:
    items = list(d.items())
    item_count = len(items)
    result = []
    for start_idx in range(item_count):
        # 取连续n个键值对,取模处理循环衔接逻辑
        current_pairs = [items[(start_idx + offset) % item_count] for offset in range(n)]
        result.append(dict(current_pairs))
    return result
测试示例
# 题目给定的原字典
d = {
    'leaf1': 1,
    'leaf2': 2,
    'leaf3': 3,
    'leaf4': 4,
    'leaf5': 5,
    'leaf6': 6
}

# 分别测试n=1、n=2、n=3的情况
print(generate_dict_list(d, 1))
print(generate_dict_list(d, 2))
print(generate_dict_list(d, 3))

运行后输出结果与题目给出的示例完全一致。

如果追求代码简洁,也可以用列表推导式简化实现:

def generate_dict_list(d: dict, n: int) -> list[dict]:
    items = list(d.items())
    item_count = len(items)
    return [dict([items[(i + k) % item_count] for k in range(n)]) for i in range(item_count)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:45:03