【问题标题】:Comparing nested list with dictionary keys and create compound key-value pair将嵌套列表与字典键进行比较并创建复合键值对
【发布时间】:2021-06-24 16:14:39
【问题描述】:

我有一个嵌套列表和一个字典,我想将列表项与字典键进行比较,如果它们匹配,则应添加相应的字典值并将其附加到同一字典新的复合键值对,如下所示:

colours = [['red', 'yellow'], ['green', 'black'], ['white', 'blue', 'orange'], ['pink', 'purple']]
dict1 = {'red': 10, 'black': 20, 'green': 30, 'neon':5, 'yellow': 40, 'orange':50, 'white':60, 
        'blue':70}

它应该将完整的子列表项与字典键进行比较,如果存在,那么应该为这些键求和字典值。

预期结果:

dict1 = {'red': 10, 'black': 20, 'green': 30, 'neon':5, 'yellow': 40, 'orange':50, 'white':60, 
        'blue':70, 'red + yellow':50, 'green + black':50, 'white + blue +orange':180}

列表被一些逻辑附加,子列表中的元素数量不固定。

在社区成员@tomjn 的帮助下,我可以部分解决这个问题,代码如下:

for i, j in itertools.combinations(itertools.chain(*colours), 2):
    if i in dict1 and j in dict1:
        dict1[f"{i} + {j}"] = dict1[i] + dict1[j]

谁能帮我完成这段代码?

提前致谢!

【问题讨论】:

  • 'neon':5 来自哪里?
  • @Barmar 感谢您的快速回复。嵌套字典中的第二个字典是附加了一些逻辑的其他字典。对不起,我已经更新了问题。'neon':5 是原始字典的一部分。
  • 是的,很抱歉它没有嵌套字典..我希望问题现在很清楚..
  • 我已经根据这个假设回答了这个问题。一小时前

标签: python


【解决方案1】:

你不需要 itertools,只需一个普通的循环 colours

for colorlist in colours:
    if (all(c in dict1 for c in colorlist)):
        dict1[" + ".join(colorlist)] = sum(dict1[c] for c in colorlist)

【讨论】:

  • 嗨@Barmar,谢谢你的回答。你能告诉我如何找到值之间的差异而不是总和吗?
  • @Sourabh functools.reduce(operator.sub, (dict1[c] for c in colorlist))
猜你喜欢
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 2017-06-21
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多