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

如何优化将扁平列表转换为字典列表的Python代码?

优化列表转字典列表的实现(无嵌套循环)

需求与示例

给定一个混合字符串和数字的列表,需将其转换为字典列表,规则如下:

  • 字符串作为字典的键
  • 键后续的数字作为对应值:单个数字直接取值,多个数字则组成列表

输入

lst = ['A', 1, 3, 4, 'B', 5, 'C', 2, 'D', 4]

预期输出

[{'A': [1, 3, 4]}, {'B': [5]}, {'C': [2]}, {'D': 4}]

现有代码(可运行但冗余)

main_array = []
small_array = []
se = {}
key = None
for i in range(len(lst)-1):
    print(i)
    if i == len(lst)-2:
        if type(lst[i]) == str and type(lst[i+1]) == str:
            main_array.append(lst[i])
            main_array.append(lst[i+1])
        elif type(lst[i]) == str and type(lst[i+1]) != str:
            main_array.append({lst[i]: lst[i+1]})
        elif type(lst[i]) != str and type(lst[i+1]) == str:
            small_array.append(lst[i])
            se.update({key: small_array})
            main_array.append(se)
            se = {}
            small_array = []
            main_array.append(lst[i+1])
        elif lst[i] != type(str) and lst[i + 1] != type(str):
            small_array.append(lst[i])
            small_array.append(lst[i+1])
            se.update({key: small_array})
            main_array.append(se)
            se = {}
            small_array = []
    else:
        if type(lst[i]) == str and i != len(lst)-1:
            if type(lst[i+1]) == str:
                main_array.append(lst[i])
            elif type(lst[i+1]) != str:
                key = lst[i]
        elif type(lst[i]) != str and i != len(lst)-1:
            if type(lst[i+1]) == str:
                small_array.append(lst[i])
                se.update({key: small_array})
                main_array.append(se)
                se = {}
                small_array = []
            elif type(lst[i+1]) != str:
                small_array.append(lst[i])
print(main_array)

优化方案(无嵌套循环)

可以通过一次线性遍历完成,记录当前键和对应的值列表,遇到新键时处理前一个键的结果,遍历结束后处理最后一个键:

def convert_to_dict_list(lst):
    result = []
    current_key = None
    current_values = []
    
    for item in lst:
        if isinstance(item, str):
            # 遇到新键,先处理之前的键值对
            if current_key is not None:
                # 根据值的数量决定是单个值还是列表
                if len(current_values) == 1:
                    result.append({current_key: current_values[0]})
                elif len(current_values) > 1:
                    result.append({current_key: current_values})
                # 清空值列表
                current_values = []
            current_key = item
        else:
            # 数字加入当前值列表
            current_values.append(item)
    
    # 处理最后一个键值对
    if current_key is not None:
        if len(current_values) == 1:
            result.append({current_key: current_values[0]})
        elif len(current_values) > 1:
            result.append({current_key: current_values})
    
    return result

# 测试
lst = ['A', 1, 3, 4, 'B', 5, 'C', 2, 'D', 4]
print(convert_to_dict_list(lst))

优化点说明

  • 仅用一次线性遍历,时间复杂度O(n),无嵌套循环
  • 逻辑清晰:通过current_key跟踪当前要处理的键,current_values收集对应数字
  • 自动处理边界情况(比如列表末尾的键值对)
  • 避免了原代码中大量的条件分支和冗余临时变量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:01:24