针对您的需求,以下是对您现有代码进行调整后的解决方案:
data = [
-1, 0,
'a','b', 1, 2, 3,
'c', 6,
'd', 'e', .4, .5,
'a', 'b', 4,
'f', 'g',
]
start = list(map(type, data)).index(str)
wanted = {}
current_group = []
current_keys = []
for i in data[start:]:
if type(i) == str:
if current_keys:
wanted['/'.join(current_keys)] = current_group
current_keys = [i]
current_group = []
else:
current_keys.append(i)
else:
current_group.append(i)
# 处理最后一个键值对
if current_keys:
wanted['/'.join(current_keys)] = current_group
print(wanted)
此代码会输出您期望的结果:
{'a/b': [1, 2, 3, 4], 'c': [6], 'd/e': [0.4, 0.5], 'f/g': []}