Operate on a list and replace values

Viewed 51

I have the list called 'list_one', which I seek to relate to 'list_relation', to finally have a final list of values, my logic is as follows:

By looping in the range of 'list_one' and for each 'items_relation' of 'list_relation':

1.If 'list_one [i] [0]' is inside 'items_relation', I add the corresponding operation of 'list_one'.

list_one = [[1,      0], 
             [2,     0], 
             [3,     0],
             [4,     0], 
             [11,    0], 
             [12,    0], 
             [13, 2000], 
             [14, 3000], 
             [15, 3500], 
             [16, 5000], 
             [17, 6500], 
             [18, 8800], 
             [19, 6700],
             [20,  280]]

# Code to get this 'list_relation' ...

list_relation = [[13, 14], [15, 16], 
                 [17, 18], [19, 20]]
             
final = []
for i in range(len(list_one)):
    for items_elements in list_relation:
        for k in items_elements:
            if list_one[i][0] in items_elements:
                final.append((list_one[i][1] + list_one[i][0]))  
print(final)

I am looking for a list like this:

[[2013, 3014], [3515, 5016], [6517, 8818], [6719, 300]]

What is the best way to do it? Thank you.

2 Answers

You can build a dictionary from list_one and then iterate to create the resulting list.

>>> d = dict(list_one)
>>> final = [[el+d[el] for el in l] for l in list_relation]
>>> final
[[2013, 3014], [3515, 5016], [6517, 8818], [6719, 300]]

list_one appears to be a lookup table - it would make more sense to use a dictionary instead of a list. Then loop through the values of list_relation, do a lookup against the dictionary and add the value if it is there. If it isn't there, get a default value of 0 so it doesn't affect the sum. This also means there is no need to include lookup entries with values of 0:

list_one = {13: 2000,  # note choose a better var name
            14: 3000, 
            15: 3500, 
            16: 5000, 
            17: 6500, 
            18: 8800, 
            19: 6700,
            20: 280,}

list_relation = [[13, 14], 
                 [15, 16], 
                 [17, 18], 
                 [19, 20]]

final = [[item + list_one.get(item, 0) 
          for item in pair] 
         for pair in list_relation]
Related