【问题标题】:Division between dicts字典之间的划分
【发布时间】:2019-04-28 17:01:22
【问题描述】:

我有两个字典:

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() }

【问题讨论】:

  • 你想要那些分数作为字符串吗?还有,dict_1dict_2 只是同一个数据的不同表达,对吧?
  • 不,我不希望这些分数作为字符串。是的,dict_1 和 dict_2 有相同的键,但是 dict_2 计算了 dict_1 值的频率。

标签: python python-3.x dictionary data-structures division


【解决方案1】:

.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 模块

【讨论】:

  • 很好,但必须有l.count(e)。如果键是“B”,则结果是 [1/2] 而不是 [1/2,1/2]。
【解决方案2】:

使用分数的版本。

from fractions import Fraction
{k: [Fraction(v[i], sum(v.values())) for i in v] for k, v in dict_2.items()}

【讨论】:

    猜你喜欢
    • 2018-10-14
    • 2013-07-04
    • 2021-11-15
    • 1970-01-01
    • 2015-11-18
    • 2017-04-13
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    相关资源
    最近更新 更多