Python在比较字典时执行计算

时间:2016-08-11 14:28:08

标签: python dictionary

我是Python的新手,我试图通过比较两个字典来执行计数和计算,但却难以将它们一起呈现。在第一次打印键和值时,有没有办法执行以下操作?

我想:

1。)检查字典x中的键是否在字典y

2。)如果密钥存在,则将键值除以两个词典的总键值,并在值旁边打印一个百分比

3。)如果密钥不存在,请自行分配密钥并在值

旁边打印一个百分比

我能够分别完成两个但不能完成。此外,如果您有提高我的代码效率的建议,我们将不胜感激。

代码:

import operator, itertools

trained = {'Dog': 4, 'Cat': 3, 'Bird': 1, 'Fish': 12, 'Mouse': 19}
untrained = {'Cat': 2, 'Mouse': 7, 'Dog': 4}

trained_list = []
untrained_list = []
print('='* 40)
print('Trained \t Untrained')
print('='* 40)
for k, v in sorted(trained.items(), key=operator.itemgetter(1), reverse=True):
    t =  (k, v  )
    trained_list.append(t)
for k, v in sorted(untrained.items(), key=operator.itemgetter(1), reverse=True):
    u =  (k, v  )
    untrained_list.append(u)
for x, y in itertools.zip_longest(trained_list, untrained_list, fillvalue="  "):
    print(str(x[0]).ljust(5, ' ') + '\t' + str(x[1]) + '\t', y[0] + '\t' + str(y[1]))

print('=' * 30)
for k,v in untrained.items():
    if k in trained:
        print('Untrained ' + str(k).ljust(5, ' ') + '\t\t' + ('{0:.2f}%').format((untrained[k]/(untrained[k] + trained[k])*100)))

print('=' * 30)

for k, v in trained.items():
    if k in untrained:
        print('Trained ' + str(k).ljust(5, ' ') + '\t\t' + ('{0:.2f}%').format((trained[k]/(untrained[k] + trained[k]))*100))
    else:
        print('Trained ' + str(k).ljust(5, ' ') + '\t\t' + ('{0:.2f}%').format((trained[k] / (trained[k])) * 100))

当前输出:

========================================
Trained      Untrained
========================================
Mouse   19   Mouse  7
Fish    12   Dog    4
Dog     4    Cat    2
Cat     3        
Bird    1        
==============================
Untrained Mouse     26.92%
Untrained Cat       40.00%
Untrained Dog       50.00%
==============================
Trained Fish        100.00%
Trained Bird        100.00%
Trained Cat         60.00%
Trained Dog         50.00%
Trained Mouse       73.08%

期望的输出:

========================================
Trained              Untrained
========================================
Mouse   19 (73.08%)  Mouse 7 (26.92%)
Fish    12 (100.00%) Dog   4 (50.00%)
Dog     4  (50.00%)  Cat   2 (40.00%)
Cat     3  (60.00%)      
Bird    1  (100.00%)

1 个答案:

答案 0 :(得分:1)

这是一个选项:

from collections import namedtuple                                         

trained = {'Dog': 4, 'Cat': 3, 'Bird': 1, 'Fish': 12, 'Mouse': 19}         
untrained = {'Cat': 2, 'Mouse': 7, 'Dog': 4}                               

Score = namedtuple('Score', ('total', 'percent', 'name'))                  

trained_scores = []                                                        
for t in trained:                                                          
    trained_scores.append(                                                 
        Score(total=trained[t],                                            
              percent=(trained[t]/(trained[t]+untrained.get(t, 0)))*100,   
              name=t)                                                      
    )                                                                      

untrained_scores = []                                                      
for t in untrained:                                                        
    untrained_scores.append(                                               
        Score(total=untrained[t],                                          
              percent=(untrained[t]/(untrained[t]+trained.get(t, 0)))*100, 
              name=t)                                                      
    )                                                                      

trained_scores.sort(reverse=True)                                          
untrained_scores.sort(reverse=True)                                        
import pprint; pprint.pprint(trained_scores)                               
import pprint; pprint.pprint(untrained_scores)

# I might name these something different.
row_template = '{:<30} {:<30}'                                          
item_template = '{0.name:<10} {0.total:>3} ({0.percent:>6.2f}%)'        
print('='*61)                                                           
print(row_template.format('Trained', 'Untrained'))                      
print('='*61)   

for trained, untrained in zip_longest(trained_scores, untrained_scores):
    print(row_template.format(                                          
        '' if trained is None else item_template.format(trained),       
        '' if untrained is None else item_template.format(untrained),   
    ))                                                                  

输出:

=============================================================
Trained                        Untrained                     
=============================================================
Mouse       19 ( 73.08%)       Mouse        7 ( 26.92%)      
Fish        12 (100.00%)       Dog          4 ( 50.00%)      
Dog          4 ( 50.00%)       Cat          2 ( 40.00%)      
Cat          3 ( 60.00%)                                     
Bird         1 (100.00%)