舍入一些元组的值

时间:2016-11-22 15:21:10

标签: python

我有这样的元组(我不确定是否会调用元组列表!)

ratings = [('5', 45.58139534883721), ('4', 27.44186046511628), ('3', 20.0), ('2', 5.116279069767442), ('1', 1.8604651162790697)]

我希望将第二个值舍入(或截断,对我来说不重要)最多2个小数位,如下所示:

[('5', 45.58), ('4', 27.44), ('3', 20.0), ('2', 5.11), ('1', 1.86)]

我试过这样的事情:

l = tuple([round(x,2) if isinstance(x, float) else x for x in ratings])

但这似乎无效。我该怎么办?

1 个答案:

答案 0 :(得分:3)

仅围绕元组的第二个元素:

ratings = [('5', 45.58139534883721), ('4', 27.44186046511628), ('3', 20.0), ('2', 5.116279069767442), ('1', 1.8604651162790697)]
l = [(item[0],round(item[1],2)) for item in ratings]
# [('5', 45.58), ('4', 27.44), ('3', 20.0), ('2', 5.12), ('1', 1.86)]