Ris*_*aur 0 python dictionary list
Keys = ['a','b','c','d','e']
values = ['a','a1','a2','b','b4','b5','c','c4','c3','d','d4','d6','e','e4','e3']
output = {'a':{'a':['a1','a2'],'b':['b4','b5'],'c':['c4','c3'],'d':['d4','d6'],'e':['e4','e3']}}
Run Code Online (Sandbox Code Playgroud)
我实现了以下代码
list4 = []
for i in range(len(values)):
for j in range(len(Keys[1:])):
if Keys[j]==values[i]:
for k in range(i,len(values)):
list4.append(values[k])
if Keys[j+1] == values[k]:
del list4[-1]
break
output = dict(zip(Keys[j], list4))
print(output)
Run Code Online (Sandbox Code Playgroud)
此逻辑不起作用,是否有任何实现?
您可以itertools.groupby为此使用:
from itertools import groupby
Keys = ['a', 'b', 'c', 'd', 'e']
values = ['a', 'a1', 'a2', 'b', 'b4', 'b5', 'c', 'c4', 'c3',
'c2', 'd', 'd4', 'd6', 'e', 'e4', 'e3']
di = {}
for k, g in groupby(values, key=lambda i: i[0]):
di[k] = list(g)[1:]
# or with dict comprehension
# di = {k:list(g)[1:] for k, g in groupby(values, key=lambda i: i[0])}
print(di)
Run Code Online (Sandbox Code Playgroud)
{'a': ['a1', 'a2'],
'b': ['b4', 'b5'],
'c': ['c4', 'c3', 'c2'],
'd': ['d4', 'd6'],
'e': ['e4', 'e3']}