-2

Considering the following 4 lists:

   x_name=[’02-2014’,’03-2014’,’05-2014’,’01-2016’,’03-2016’]
   x_value=[5,7,10,5,8]

   z_name=[’02-2014’,’03-2014’,’04-2014’,’05-2014’,’07-2014’,’01-   
        2016’,’02-2016’,’03-2016’]
   z_value=[16,18,33,12,78,123,3,5]

From these 4 lists, I would like to have two lists of e.g., lst_name and lst_value. The inside of lst_name should be the same as z_name, but for lst_value, if they have the identical names in (x_name and z_name), we should calculate the ratio of their corresponding values (in x_value and z_value) e.g., 5/16, and the names in z_name which are not in x_name (e.g., ’04-2014’, ’02-2016’,etc), should be assign to 0 in the lst_value list. So the desired list should be:

lst_name=[’02-2014’,’03-2014’,’04-2014’,’07-2014’,’05-
             2014’,’01-2016’,’02-2016’,’03-2016’]

Lst_value=[0.31,0.38,0,0.83,0,0.06,0,1.6]

Any idea to handle it in an efficient way?

Spedo
  • 355
  • 3
  • 13

1 Answers1

1

CODE

from __future__ import print_function


x_name = ['02-2014', '03-2014', '05-2014', '01-2016', '03-2016']
x_value = [5, 7, 10, 5, 8]

z_name = ['02-2014', '03-2014', '04-2014', '05-2014',
          '07-2014', '01-2016', '02-2016', '03-2016']
z_value = [16, 18, 33, 12, 78, 123, 3, 5]


Lst_value = []

if len(z_name) > len(x_name):
    lst_name = z_name
    other = x_name
else:
    lst_name = x_name
    other = z_name

for n, elem in enumerate(lst_name):
    if elem in other:
        m = other.index(elem)
        Lst_value.append(float(x_value[m])/z_value[n])

    else:
        Lst_value.append(0.0)

print(Lst_value)

OUTPUT

lst_name = ['02-2014', '03-2014', '04-2014', '05-2014', '07-2014', '01-2016', '02-2016', '03-2016']
Lst_value = [0.3125, 0.3888888888888889, 0.0, 0.8333333333333334, 0.0, 0.04065040650406504, 0.0, 1.6]
Sven-Eric Krüger
  • 1,277
  • 12
  • 19