假设我有以下列表:
mylist = [keyobj1, valobj1, valobj2, keyobj2, valobj1, valobj2, valobj3,...]
我想从中得到一个字典,其中包含:
mydict = {keyobj1: [valobj1, valobj2], keyobj2: [valobj1,valobj2,valobj3, ...}
是否有执行此任务的库?
下面是要执行的粗略算法(我知道,看起来很难看):
# convert mylist to iterator
mylist = iter(mylist)
n = mylist.next()
while True:
try:
if not iskey(n):
n = mylist.next()
value_list.append(n)
else:
mydict[key] = value_list
value_list = []
key = n
n = mylist.next()
except StopIteration:
mydict[key] = value_list
break