gpt4 book ai didi

Python 在比较字典的同时执行计算

转载 作者:太空宇宙 更新时间:2023-11-03 16:16:40 24 4
gpt4 key购买 nike

我是 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%)

最佳答案

这里有一个选项:

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%)

关于Python 在比较字典的同时执行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38899178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com