2

假设我有以下列表:

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
4

1 回答 1

5

我会这样做:

mydict = defaultdict(list)
sublist = None
for item in mylist:
    if iskey(item):
        sublist = mydict[item]
    else:
        sublist.append(item)

我想到使用的唯一库是collections, for defaultdict

于 2013-10-10T13:52:05.077 回答