Search code examples
pythonarrayslistjython

Calculating Difference from two different lists in Python


I have two different sets of Lists and new list always have new value and i want to know how much the value has changed ?

previous=[ [525, 'test', 'A3'],[522, 'test', 'A4']]

current = [ [525, 'test', 'A3'],[622, 'test', 'A4'],[320, 'test', 'A5']]

for A4 the difference is 100 How can able to calculate the difference ?

Desired output:

 A4 = 100
 A5 = 320

Solution

  • This code could solve your problem (I followed the idea of Chris Charley to use a dictionary in order to map the keys A3, A4, ... to their integer values for each entry in the previous variable).

    from operator import itemgetter
    
    previous=[ [525, 'test', 'A3'],[522, 'test', 'A4']]
    current = [ [525, 'test', 'A3'],[622, 'test', 'A4'],[320, 'test', 'A5']]
    
    def differences():
        d = dict(map(itemgetter(2, 0), previous))
        for key, value in map(itemgetter(2, 0), current):
            difference = abs(d.get(key, 0) - value)
            if difference > 0:
                yield key, difference
    
    output = dict(differences())
    

    The output will be:

    {'A4': 100, 'A5': 320}
    

    differences() its a generator function that returns for each entry in the current list, a tuple with two items: The key A* and the amount of change between the previous and current lists (only if the difference is not 0) e.g: ('A4', 100)