坚持尝试从 2 个列表创建新字典 - 1 个元组,1 个用于字典键

Stuck trying to create new dictionary from 2 lists - 1 of tuples, 1 for dictionary keys

我有 2 个列表。 a 是一个元组列表,我想将其转换为将 'a' 值保留为列表的字典 - 使用第二个列表作为字典键。我尝试使用 a's 首先在元组列表中设置为 'index' 值来与 b 列表中的 'key' 值结合。 这是我的:

a = [(0, ['Potato'], [8]),
     (0, ['Tomato'], [2]),
     (0, ['Tomato'], [2]),
     (0, ['Potato'], [6]),
     (0, ['Potato'], [12]),
     (0, ['Potato'], [12]),
     (0, nan, nan),
     (1, [], []),
     (1, [], [])]

b = [('foo', 123), ('bar', 456)]

这就是我想要得到的:

newDict = {'foo' : [(['Potato'], ['Tomato'], ['Tomato'], ['Potato'], ['Potato'], ['Potato'], nan), ([8], [2], [2], [6], [12], [12], nan)], 
           'bar' : [([], []),([],[])]}

我尝试通过各种 for 循环枚举,解压缩元组。

您可以使用分组依据(来自 itertools)根据第一个条目对 a 中的元组进行分组,然后将其压缩到 b 以配对 'foo' 和 'bar'对应0组和1组:

a = [(0, ['Potato'], [8]),
     (0, ['Tomato'], [2]),
     (0, ['Tomato'], [2]),
     (0, ['Potato'], [6]),
     (0, ['Potato'], [12]),
     (0, ['Potato'], [12]),
     (0, 'nan', 'nan'),
     (1, [], []),
     (1, [], [])]

b = [('foo', 123), ('bar', 456)]


from itertools import groupby

r = {tb[0]:list(zip(*ta))[1:] for tb,(_,ta) in zip(b,groupby(a,lambda t:t[0]))}

print(r)
{'foo': 
  [(['Potato'], ['Tomato'], ['Tomato'], ['Potato'], ['Potato'], ['Potato'], 'nan'), 
   ([8], [2], [2], [6], [12], [12], 'nan')], 
 'bar': 
  [([], []), ([], [])]}