【问题标题】:Stuck trying to create new dictionary from 2 lists - 1 of tuples, 1 for dictionary keys试图从 2 个列表创建新字典 - 1 个元组,1 个用于字典键
【发布时间】:2021-12-25 02:02:50
【问题描述】:

我有 2 个列表。 a 是一个元组列表,我想将其转换为一个将“a”值保留为列表的字典 - 使用第二个列表作为字典键。我尝试使用 a's 第一个设置为元组列表中的“索引”值来与 b 列表中的“键”值结合。 这就是我所拥有的:

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 循环,解压缩元组。

【问题讨论】:

  • 逻辑似乎不一致。为什么在输出 [[], []] 而不是 [[[], []], [[], []]]?我的意思是,输入中有 四个 空列表,那么其中两个去了哪里?
  • 示例更新
  • 为什么是'Patato' 而不是['Patato']——原来的值是什么?
  • 我认为如果我们在索引为 0 的列表上按模式分组,前面的例子会更有意义。
  • 结果没有改变,在输出中调整了格式以反映'a'中的格式

标签: python list dictionary tuples


【解决方案1】:

您可以使用 group by(来自 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': 
  [([], []), ([], [])]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    相关资源
    最近更新 更多