gpt4 book ai didi

python - 字典之间的划分

转载 作者:行者123 更新时间:2023-11-28 20:55:48 25 4
gpt4 key购买 nike

我有两个指令:

dict_1 = {'A': ['red', 'red', 'blue'],
'B': ['red', 'green'],
'C': ['blue', 'green'], ....}

dict_2 = {'A': Counter({'red': 2, 'blue': 1}),
'B': Counter({'red': 1, 'green': 1}),
'C': Counter({'blue': 1, 'green': 1}), ....}

我需要在它们之间做一些简单的划分,然后将它们成对绘制。期望的结果是这样的或者任何可以做除法的东西:

fraction = {'A': [2/3, 1/3],
'B': [1/2, 1/2],
'C': [1/2, 1/2], ....}

目前,我只能得到第一位数字,任何建议将不胜感激!这是我的代码:

fraction = { key: [v/len(colorz)] for namez, colorz in dict_1.items() 
for name, color in dict_2.items()
for k, v in color.items() }

最佳答案

.countpretty fast ,所以我没有将 dict_2Counter 一起使用,但可以使用它。

fraction = {k: [l.count(e)/len(l) for e in set(l)] for k, l in dict_1.items()}

但这意味着简短不一定有效。如果需要更快,您可以做其他事情。如果你想把它们作为字符串,那么

fraction = {k: [f'{e.count(l)}/{len(l)}' for e in set(l)] for k, l in dict_1.items()}

如果你想要它们作为减少分数的字符串,使用 fraction模块

关于python - 字典之间的划分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55892615/

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