我的以元组为键的字典如下:

键代表x和y坐标。 (x,y)

D1 = {(10,12): 23, (8,14): 45, (12, 9): 29}
D2 = {(2, 8) : 67, (12, 10): 23, (14, 8): 56}


现在,根据以上字典,我想执行以下操作


根据键对字典D1进行排序
根据键对字典D2进行排序
只需在D1中打印键和值
只需在D2中打印键和值
然后执行以下操作:


(伪代码)

total = 0
For each key (x, y) in D1,
   if D2.has_key((y, x)):
      total = total + D1[(x, y)] * D2[(y, x)]
   Print total

最佳答案

(1/2)要对字典进行排序,必须使用collections.OrderedDict(因为未对常规字典进行排序)
码:

from collections import OrderedDict
D1 = {(10,12): 23, (8,14): 45, (12, 9): 29}
D1_sorted = OrderedDict(sorted(D1.items()))

(3/4)代码:print(D1)
(5)将您的代码转换为python

total = 0
for x, y in D1.keys():
    try:
        total = total + D1[(x, y)] * D2[(y, x)]
    except KeyError:
        pass
print total

关于python - 以Tuple为键解析字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16776806/

10-15 01:02