如何在python中将参数传递给mapper函数?

我有一本字典如下,

ex_dict={ 'age':[56.96078431372548, 56.4, 3.072112285489562, 55.1, 58.1, 3.0,0.3041844431225945], 'weight':[92.68823529411763, 92.85, 3.5100777634435665, 90.7, 94.75, 4.049999999999997, 0.3475494873130708]}

我想四舍五入每个键值的值,如下面的代码所示

{k:list(map(np.round,v)) for k,v in ex_dict.items()}   

它给出的输出为

{'age':[57.0、56.0、3.0、55.0、58.0、3.0、0.0],    '权重':[93.0,93.0,4.0,91.0,95.0,4.0,0.0]}

在这里,我应该如何将参数(小数为2)传递给map中给出的np.round函数?

评论
  • cet
    cet 回复

    You can directly use np.round() on your list, without using the map() function.

    Change list(map(np.round,v)) to simply np.round(v, decimals=2).

    np.round() can be applied on array-like data, so it can be applied on the entire list instead of element-by-element.

  • 烟花落
    烟花落 回复

    尝试这个:

    import numpy as np
    
    ex_dict={ 'age':[56.96078431372548, 56.4, 3.072112285489562, 55.1, 58.1, 3.0,0.3041844431225945], 'weight':[92.68823529411763, 92.85, 3.5100777634435665, 90.7, 94.75, 4.049999999999997, 0.3475494873130708]}
    
    print({k:list(map(lambda x: np.round(x,2),v)) for k,v in ex_dict.items()})
    

    输出:

    {'age': [56.96, 56.4, 3.07, 55.1, 58.1, 3.0, 0.3], 'weight': [92.69, 92.85, 3.51, 90.7, 94.75, 4.05, 0.35]}