Home > OS >  Python merge 2 lists
Python merge 2 lists

Time:06-29

pricelist=[373, 381, 398, 402, 404, 457, 535, 550, 566]
pricelist2=[97, 00, 98, 98, 98, 97, 99, 97, 98]

I would like to merge these 2 lists (strings) into the following :

final_price=[373.97, 381.00, 398.98] etc

So join the prices together and add a dot. Pls help

EDIT, Sorry I forgot to mention that the lists are currently strings

CodePudding user response:

You can use zip and a list comprehension:

pricelist=[373, 381, 398, 402, 404, 457, 535, 550, 566]
pricelist2=[97, 0, 98, 98, 98, 97, 99, 97, 98]

out = [a b/100 for a,b in zip(pricelist, pricelist2)]

output:

[373.97, 381.0, 398.98, 402.98, 404.98, 457.97, 535.99, 550.97, 566.98]

NB. as pointed out by @OlvinRoght if you plan to use the representation of the output number, better round to avoid floating point precision issues (for example 6 94/100 would give 6.9399999999999995)

out = [round(a b/100, 2) for a,b in zip(pricelist, pricelist2)]

numpy

You might also be interested in using a specialized library. numpy can handle arrays/vectors very efficiently:

import numpy as np
a1 = np.array(pricelist)
a2 = np.array(pricelist2)

out = a1 a2/100

output:

array([373.97, 381.  , 398.98, 402.98, 404.98, 457.97, 535.99, 550.97,
       566.98])
  • Related