Protoss Reed
Protoss Reed

Reputation: 265

Python formating all values in list of lists

I am so sorry that I asking so silly question but could you help me please format list of lists ("%.2f") for example:

a=[[1.343465432, 7.423334343], [6.967997797, 4.5522577]]

I used:

  for x in a:
     a = ["%.2f" % i for i in x]
     print (a)

OUT:

['1.34', '7.42']
['6.97', '4.55']

But I would like to get my list of lists OUT:

[['1.34', '7.42'] ,['6.97', '4.55']]

Upvotes: 0

Views: 71

Answers (2)

VPfB
VPfB

Reputation: 17342

A more general solution requires just a few lines. It recursively formats numbers, lists, lists of lists of any nesting depth.

def fmt(data):
    if isinstance(data, list):
        return [fmt(x) for x in data]
    try:
        return "%.2f" % data
    except TypeError:
        return data


a=[[1.343465432, 7.423334343], [6.967997797, 4.5522577], [10, [20, 30]], 40] 
print(fmt(a))
# [['1.34', '7.42'], ['6.97', '4.55'], ['10.00', ['20.00', '30.00']], '40.00']

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48100

In a simpler way, you may achieve the same using list comprehension as:

>>> a=[[1.343465432, 7.423334343], [6.967997797, 4.5522577]]
>>> [["%.2f" % i for i in l] for l in a]
[['1.34', '7.42'], ['6.97', '4.55']]

Infact even your code is fine. Instead of print, you need to just append the values you are printing to a list

Upvotes: 2

Related Questions