KidSudi
KidSudi

Reputation: 492

Rounding numbers in a list of lists

I am trying to round all the numbers to two decimal places in a list of lists as below:

a = [[4.5555, 5.6666, 8.3365], [10.4345, 1.574355. 0.7216313]]
b = [x for x in a for y in [round(z, 2) for z in x]]

I am trying to use a list comprehension to do this, but cannot get it going. The b variable just returns the same thing as a. Is this the best way to go about it? Is there a better alternative way? Thanks!

Upvotes: 1

Views: 10455

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You can just call np.round on your list of lists, no need for a comprehension

import numpy as np
a = ([[4.5555, 5.6666, 8.3365], [10.4345, 1.574355, 0.7216313]])
print np.round(a,2)
[[  4.56   5.67   8.34]
 [ 10.43   1.57   0.72]]

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601679

Your tags suggset that a is actually a Numpy array and not a nested Python list. In that case, you can use the round() method on the array object to get a rounded copy of the array:

>>> a = numpy.random.randn(3, 3)
>>> a
array([[ 1.46998835,  0.62139675,  0.37665545],
       [-0.79925019, -0.51251798,  1.36500036],
       [ 0.66339687, -1.22586919,  1.68054346]])
>>> a.round(3)
array([[ 1.47 ,  0.621,  0.377],
       [-0.799, -0.513,  1.365],
       [ 0.663, -1.226,  1.681]])

You can round the array in place, without creating a copy, using a.round(3, out=a).

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122122

You need to nest your list comprehensions:

[[np.round(float(i), 2) for i in nested] for nested in outerlist]

The outer list comprehension loops over your outer list object, then applies an inner list comprehension for each sublist. This nested comprehension is something you apply to produce a new sublist, so you put it on the left-hand side.

Upvotes: 8

Related Questions