代码之家  ›  专栏  ›  技术社区  ›  ah bon

将字典值的数据类型从浮点转换为带两位小数的百分比,删除一些标点符号

  •  1
  • ah bon  · 技术社区  · 3 年前

    假设我有一本字典 d ,值的数据类型为 float ,因为此值为 准确率 。所以我想将其转换为 percentage :

    d = {'import': 0.5833333333333334, 'export': 0.4166666666666667}
    d.values()
    d.items()
    for k, v in d.items():
         d[v] = d[format(v,'.2%')]
    

    最终目标是删除键上的引号和大括号,并将其转换为字符串以传递matplotlib图的标题:

    plt.title(f"Models accuracy is :\n{str(d)}")
    

    该图的标题将变成这样:

    Models accuracy is :
    import: 58.33%, export: 41.67%
    

    如何做到这一点?

    1 回复  |  直到 3 年前
        1
  •  1
  •   Robbie    3 年前

    类似于:

    # format each metric
    # this will give you 2 decimal places
    results = [f"{key}:{100*d[key]:.2f}%" for key in d]
    
    # combine into a single string
    results_combined = ", ".join(results)
    
    # set as title
    title = f"Models accuracy is :\n{results_combined}"