我有包含字符串和数字的列表。如果它是字符串,我正在尝试根据类型转换为字典,否则它将成为键。
输入:
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/