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

如何从含重复元素的列表生成多个动态字典,以元素下标为键

原代码问题

  • 硬编码仅判断x == "A",无法自动识别所有连续相同元素分组
  • while循环逻辑错误,遍历到A元素时会进入死循环,index会直接超出列表长度,无法正常遍历后续元素
  • 仅定义了一个字典变量,无法生成多个分组对应的独立字典

正确实现

方案1:使用itertools.groupby(最简洁)

itertools.groupby原生支持对连续相同元素分组,实现代码如下:

import itertools

theList = ['A', 'A', 'B', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'D', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'F', 'F', 'F']

# 按元素值对(索引, 值)对分组
for _, group in itertools.groupby(enumerate(theList), key=lambda item: item[1]):
    # 索引从1开始计数,生成对应字典
    group_dict = {idx + 1: val for idx, val in group}
    print(group_dict)

方案2:手动遍历实现(无第三方依赖)

如果不想引入内置库,也可以手动遍历列表处理分组:

theList = ['A', 'A', 'B', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'D', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'F', 'F', 'F']

if not theList:
    exit()

# 初始化第一个分组
current_val = theList[0]
current_dict = {1: current_val}

for idx in range(1, len(theList)):
    current_element = theList[idx]
    if current_element == current_val:
        # 元素和当前分组值相同,加入当前字典
        current_dict[idx + 1] = current_element
    else:
        # 元素不同,输出当前分组,初始化新分组
        print(current_dict)
        current_val = current_element
        current_dict = {idx + 1: current_element}

# 输出最后一个分组
print(current_dict)

两种方案运行后都可以得到你期望的输出结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:54:02