Round numbers with flask.jsonify

Here is an array with Prediction namedtuplethat I am returning with flask.jsonify.

y = current_app.extensions['classifier'].classify(url=maybe_image_url)
return jsonify(y=y)

What would be the best way to round the probability percentage to two decimal places?

[Prediction(rank=1, category='dog', probability=0.99999475479125977), Prediction(rank=2, category='sheep', probability=5.2518985285132658e-06), Prediction(rank=3, category='cat', probability=1.3360376693860587e-10)]
+4
source share
1 answer

namedtupleare immutable (because they are tuples, and this is quite a lot of tuples), so you cannot do the job, but they have a good method called _replaceto create a copy with the corresponding value, modified.

y = [p._replace(probability=round(p.probability, 2)) for p in y]
+2
source

Source: https://habr.com/ru/post/1661108/


All Articles