Home > OS >  Compare two lists with custom functions and custom comparison
Compare two lists with custom functions and custom comparison

Time:02-04

I have two lists

a = [1,2,3]
b = [2,3,4,5]

and two custom functions F1(a[i]) and F2(b[j]), which take elements from lists a and b return objects, say A and B. And there is a custom comparison function diff(A,B), which returns False if the objects are the same in some sense and True if they are different. I would like to compare these two lists in a pythonic way to see if the lists are the same. In other words, that all objects A generated from list a have at least one equal object B generated from list b. For example if the outcome is the following then the lists are the same:

(diff(F1(1),F2(4)) or diff(F1(1),F2(5)) or diff(F1(2),F2(3)) or diff(F1(3),F2(2))) is False

For the function sorted there is a key function. Are there any comparison functions in Python that can take a custom function in this situation? The only solution that I see is to loop through all elements in a and loop through all elements in b to check them element by element. But then if I want to extend the functionality this would require quite some development. If there is a way to use standard Python functions this would be very much appreciated.

CodePudding user response:

all(True if any(diff(A, B) is False for B in [F2(j) for j in b]) else False for A in [F1(i) for i in a])

Honestly I just typed this quickly using my Python auto-pilot but it would look something like this I guess.

CodePudding user response:

Probably the best you can get is first converting all entries of the list, and then iterate over both and check if any of a has a match in b and if that holds true for all as. So something like

af = [F1(i) for i in a]
bf = [F2(i) for i in b]
is_equal = all(any(not diff(a,b) for b in bf) for a in af )

all stops as soon as it finds the first value that is false, any stops as soon as it finds the first value that is True.

  •  Tags:  
  • Related