chanwcom
chanwcom

Reputation: 4680

How to apply formatted printing to a python list?

Suppose that I have a list of floating-point numbers in Python.

x = [1.2, 3.4, 5.7, 7.8]

To print out this array, we may use the following command:

print '{0}'.format(x)

The output of the above command is as follows:

[1.2, 3.4, 5.7, 7.8]

But, is there a way to print out the contents of the list in a formatted way? For example, I'd like to use four decimal points as follows:

[ 1.2000,  3.4000,  5.7000,  7.8000]

To do this, I may use the following commands, but it is obviously too messy, and I think there might be some simple ways of doing this.

print '[',
for i in range(0, len(x) - 1):
  print '{0:5.4f}, '.format(x[i]),
print '{0:5.4f}]'.format(x[len(x) - 1])

Could anyone please give me some suggestion on this?

Upvotes: 0

Views: 801

Answers (3)

Anton Protopopov
Anton Protopopov

Reputation: 31692

Alternative to format you could also use %:

l = [1.2, 3.4, 5.7, 7.8]

In [182]: list(map(lambda x: '%.4f' % x, l))
Out[182]: ['1.2000', '3.4000', '5.7000', '7.8000']

With timing you could see that % a bit faster then format output:

In [189]: %timeit list(map(lambda x: '%.4f' % x, l))
100000 loops, best of 3: 3.96 us per loop

In [190]: %timeit list(map('{0:5.4f}'.format,l))
100000 loops, best of 3: 4.69 us per loop

In [192]: %timeit ['{0:5.4f}'.format(i) for i in x]
100000 loops, best of 3: 12.4 us per loop

Upvotes: 1

Ahasanul Haque
Ahasanul Haque

Reputation: 11164

You can use map

print map('{0:5.4f}'.format,x)

In case, you are using python 3, do:

print list(map('{0:5.4f}'.format,x))

Upvotes: 2

TerryA
TerryA

Reputation: 60024

Use a list comprehension:

>>> x = [1.2, 3.4, 5.7, 7.8]
>>> x1 = ['{0:5.4f}'.format(i) for i in x]
>>> x1
['1.2000', '3.4000', '5.7000', '7.8000']

A list comprehension is a flattened version of something that would look like this:

>>> x1 = []
>>> for i in x:
...     x1.append('{0:5.4f}'.format(i))
... 
>>> x1
['1.2000', '3.4000', '5.7000', '7.8000']

Upvotes: 3

Related Questions