I have a function for calculate closest value between sublists. But i need to find only one value for each sublist, considering the threshold. What can i do?
eee=[[22,27,28],[23,18,38]]
www=[[30],[20]]
xx1=[]
for ee, ww in zip(eee, www):
for w in ww:
xx=[]
for e in ee:
cc = abs(e - w)
if -7 <= cc <= 7:
xx.append(e)
xx1.append(xx)
print(xx1)
The expected values could be:
[[28],[18]]
Since your www
variable is a list of lists rather than a list of integers, each of its sub-lists can potentially hold more than one value even though there is only one value in each sub-list in your example. If there can indeed be more than one value in each sub-list in www
, I would suggest that you use itertools.product
to produce all the combinations of each item in the corresponding sub-lists of the two lists, and then use the min
function with a key function that returns the distance between each pair of values to find the item in each sub-list of eee
that's closest to any item in the corresponding sub-list in www
:
from itertools import product
from operator import sub
[min(product(e, w), key=lambda p: abs(sub(*p)))[0] for e, w in zip(eee, www)]
This returns:
[28, 18]