簡體   English   中英

比較兩個字典並打印差異

[英]Compare Two Dictionaries and Print Difference

我已經計算了兩個字典的值之間的差異。 我目前所做的工作,但我想將“dict1[x] - dict2[x]”打印到我在結果前面寫入的文件中。 不僅僅是結果。 我怎樣才能做到這一點? 我需要嵌套循環嗎?

comparison = {x: dict1[x] - dict2[x] for x in dict1 if x in dict2}

file1 = open('Results.txt', 'w')
for key,value in comparison.iteritems():
    print >> file1, ('%s: %s' % (key,value)) 
file1.close()

編輯:示例

每個字典中存儲的值是時間戳,所以我希望我的最終結果如下所示:

12:30-11:30 = 1:00 

您可以將dict1[x]dict2[x]元組dict1[x] dict 的鍵,並在迭代 dict 項時相應地解包:

comparison = {(dict1[x], dict2[x]): dict1[x] - dict2[x] for x in dict1 if x in dict2}

file1 = open('Results.txt', 'w')
for (time1, time2), value in comparison.iteritems():
    print >> file1, ('%s-%s: %s' % (time1, time2, value)) 
file1.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM