假设我有以下列表:
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
答案 0 :(得分:5)
我这样做:
mydict = defaultdict(list)
sublist = None
for item in mylist:
if iskey(item):
sublist = mydict[item]
else:
sublist.append(item)
我发现的唯一一个库是collections
,defaultdict
。