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)

有没有什么方法可以优化这段代码,因为我打算避免嵌套循环?

最佳答案

最好创建一个中间字典,然后将该字典转换为您想要的结果。像这样:

import collections

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

dct = collections.defaultdict(lambda: [])
key = None
for el in lst:
    if type(el) == str:
        key = el
        continue
    dct[key].append(el)

result = [{key: dct[key]} for key in dct]
print(result)

https://stackoverflow.com/questions/74230193/

相关文章:

c - 在分配内存之前对灵活成员数组的第一个元素使用 sizeof 是未定义的行为?

node.js - react native : A failure occurred while

c++ - 如何使用索引初始化数组元素

haskell - 如何声明一个参数可以是 (Int, Int) 或 Maybe (Int, Int

python - 列表到列表字典(Python 优化)

powershell - 执行功能默认操作,除非给出管道输入?

r - 如何合并两个数据框并提取列的唯一组合?

r - 使用 group_by() 根据条件折叠 R 中的数据集

php - 按列中的子数组对数据行进行分组,并创建具有可变深度的子集

r - 更快地填充矩阵