In this post, we are going to construct a unit conversion table in python. The table will have columns for meters (m), centimeter (cm), and inches (in). We will start off with a list of values that will be our meter collumn.


In [1]:
meters = [0, 10, 20, 30, 40, 50]

In [2]:
meters


Out[2]:
[0, 10, 20, 30, 40, 50]

In [5]:
centimeters = meters*0.01
centimeters


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5c4be8cc688b> in <module>()
----> 1 centimeters = meters*0.01
      2 centimeters

TypeError: can't multiply sequence by non-int of type 'float'

One way we can accomplish this is with list comprehensions.


In [7]:
centimeters = [value*100 for value in meters]
centimeters


Out[7]:
[0, 1000, 2000, 3000, 4000, 5000]

We can also create our originol meter list in a more dynamic way.


In [3]:
meters = list(range(11))
meters = [value*10 for value in meters]
meters


Out[3]:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Another way to accomplish this same thing is to use numpy's array function


In [4]:
import numpy as np

In [10]:
meters = np.arange(0,110,10)
meters


Out[10]:
array([  0,  10,  20,  30,  40,  50,  60,  70,  80,  90, 100])

Now making the centimeters list is a little easier, because we can multiply each value in the array by the scalar 100 with one opperation and no need for list comprehensions.


In [11]:
centimeters = meters*100
centimeters


Out[11]:
array([    0,  1000,  2000,  3000,  4000,  5000,  6000,  7000,  8000,
        9000, 10000])

In [20]:
table = np.concatenate((meters,centimeters),axis=0)
print(table)


[    0    10    20    30    40    50    60    70    80    90   100     0
  1000  2000  3000  4000  5000  6000  7000  8000  9000 10000]

In [28]:
np.reshape(table,(2,11))
table


Out[28]:
array([    0,    10,    20,    30,    40,    50,    60,    70,    80,
          90,   100,     0,  1000,  2000,  3000,  4000,  5000,  6000,
        7000,  8000,  9000, 10000])

In [29]:
table.shape


Out[29]:
(22,)

In [ ]: