2

My intention is to get [[1.23,2.45],[2.35,9.87]).
The following gives one single element to be 1.23, why is this so?

b =[[1.234,2.454],[2.352,9.873]]

def get_round(x):
    for i in x:
        if type(i) ==list:
            for each_i in i: 
                return round(each_i,2)
        else:
            return round(i,2)

get_round(b)   

How can I round every single elements and without change the existing data structure?

martineau
  • 119,623
  • 25
  • 170
  • 301
leon sun
  • 21
  • 1
  • 3

1 Answers1

3

Here is a nice pythonic way to do this

func = lambda x: round(x,2)

b =[[1.234,2.454],[2.352,9.873]]
b = [list(map(func, i)) for i in b]
print(b)

[[1.23, 2.45], [2.35, 9.87]]

This will create a temporary function which will round a single value to 2 decimal places. We call this function func. Now we want to apply this function to each list in a list so we iterate through our outer list and extract each list inside it. Then we use the map function to apply func to every single element inside this list. We then convert our map iteratable object to a list and we have our answer.


Doing things your way

b =[[1.234,2.454],[2.352,9.873]]

def get_round(x):
    temp = []
    for i in x:
        if type(i) ==list:
            x = []
            for each_i in i: 
                x.append(round(each_i,2))
            temp.append(x)
        else:
            temp.append(round(i,2))
    return temp

print(get_round(b))

In your original code you were returning too soon. You find the first number in your list of lists, convert it, then return it. This goes back to where we called the function from.

JahKnows
  • 2,618
  • 3
  • 22
  • 37