我怎样才能找到字典中所有值之间的差异?(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-v2A 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更多推荐
发布评论