我怎样才能找到字典中所有值之间的差异?(How can I find all the differences between values in a dictionary?)

编程入门 行业动态 更新时间:2024-10-26 06:35:09
我怎样才能找到字典中所有值之间的差异?(How can I find all the differences between values in a dictionary?) python

说我有一本字典:

dictionary = {'A':3,'B',8,'C',12}

我怎么能通过字典循环,找到每个值之间的差异并保存结果。

例如,我想(不用硬编码)使用上面的字典返回如下字典:

differences = {'A_minus_B':-5,'B_minus_A':5, 'A_minus_C':-8,'C_minus_A':8, 'C_minus_B':4,'B_minus_C':-4}

我可以对它进行硬编码,但我希望我的函数更具动态性,这样我就可以添加更多元素,而无需编写繁琐的代码行来合并新元素。

Say I have a dictionary:

dictionary = {'A':3,'B',8,'C',12}

How could I loop through the dictionary such I that find the difference between each value and save the results.

For example, I want to (without hardcoding it) return a dictionary like the following using the dictionary above:

differences = {'A_minus_B':-5,'B_minus_A':5, 'A_minus_C':-8,'C_minus_A':8, 'C_minus_B':4,'B_minus_C':-4}

I can hardcode it but I would like my function to be more dynamic so that I can add more elements without having to write tedious lines of code to incorporate a new element.

最满意答案

一个可行但丑陋的循环解决方案:

differences = dict() for k1,v1 in dictionary.items(): for k2,v2 in dictionary.items(): if k1==k2: continue differences[k1 + '_minus_' + k2] = v1-v2

A workable yet ugly loop solution:

differences = dict() for k1,v1 in dictionary.items(): for k2,v2 in dictionary.items(): if k1==k2: continue differences[k1 + '_minus_' + k2] = v1-v2

更多推荐

本文发布于:2023-04-28 00:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329213.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   差异   find   dictionary   values

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!