Search code examples
pythonlistcomparedelta

compare two lists of lists of float, return the first delta with the associated name


I work on a project on python and I need to return the first delta beetween two lists of lists. And each position in the inside list refer to a name.

I succeed to return all the delta with the corresponding name and the first delta alone, but I would like to stop at the first delta found and return it with the corresponding name.

My actual code is :

l_name = ["ALPHA", "BETA", "CHARLIE"]         # the list of names
liste1 = [[1, 2, 3.0001], [2,5.045,6.005], [3, 8.03, 9], [4, 10.5, 5.5]]   
liste2 = [[1, 2, 3.0], [2,5.046,6.005], [3, 8.0029, 9], [4, 10.5, 5.55]]
abs_tol = 0.00001                # tolerence to found a delta

def isclose(a, b, abs_tol):      # to calculate the delta beetween each value at the same position 
                                 # in each list
    delta = abs(a-b)
    if delta >= abs_tol:
        print(delta)
    else:
        print("No delta")

l_del = []                       # prepar for a list of delta found
def found_delta(name):
    s = len(liste1)
    t = len(liste2)
    if s <=t :                      # in case the length is not the same
        for i in range(s):
            for j in range(len(l_name)):
                print("the name {}".format(l_name[j]))
                l_del.append(isclose(liste1[i][j], liste2[i][j], abs_tol))
    else:
        for i in range(t):
            for j in range(len(l_name)):
                print("the name {}".format(l_name[j]))
                l_del.append(isclose(liste1[i][j], liste2[i][j], abs_tol))
    print(l_del)
    return l_del

found_delta(l_name)

l_delta = []
for in range(len(l_del)):
    if l_del[i] != None:
        l_delta.append(l_del[i])

print("la liste des deltas est : {}".format(l_delta))
print("le premier delta est {}".format(l_delta[0]))

So I have in Output :

the name ALPHA
No delta
the name BETA
No delta
the name CHARLIE
0.0001
the name ALPHA
No delta
the name BETA
0.001
the name CHARLIE
No delta
the name ALPHA
No delta
the name BETA
0.0271
...
[None, None, 0.0001, None, 0.001, None, None, 0.0271, None, ...]
la liste des deltas est : [0.0001, 0.001, 0.0271, 0.05]
le premier delta est 0.0001

But I would like only :

CHARLIE is the name with the first delta : 0.0001

And if possible to stop to compare the others values when the first delta is found.

If anyone have an idea I'll be really greatfull.

Alex.


Solution

  • Seems like this is what you might need :

    for name, list1, list2 in zip(l_name, liste1, liste2):
        for item1, item2 in zip(list1, list2):
            diff = abs(item1 - item2)
            if diff <= abs_tol and item1 != item2:
                print(f"{name} is the name with the first delta : {diff}")
                break