Reputation: 21
Here is my code to get the nearest value to a given number ( Mynumber) from a list (Mylist)
Mylist= [ 1, 2, 3]
Mynumber=3
takeClosest = lambda num,collection:min(collection,key=lambda x:abs(x-
num))
closest= [takeClosest(Mynumber,Mylist)]
print closest
Now I have 3 lists [ 1, 2, 3] ,[ 4, 7, 8], [ 13, 9, 10] I want to compare first item , second item and 3rd item of them with this list,[2,6,9] ,If I compare 1st item in each list, out if [1,4,13], 1 is the closest to 2 ,If I compare 2nd item in each list, out of [2,7,9], 7 is the closest to 6,If I compare 3rd item in each list, out of [3,8,10], 10 is the closest to 9 Does any one know how to do it? Any suggestion would be greatly appreciated
"""
Mylist1= [ 1, 2, 3]
Mylist2= [ 4, 7, 8]
Mylist3= [ 13, 9, 10]
Mynumber=[2,6,9]
"""
Upvotes: 0
Views: 81
Reputation: 12679
You can try something like this:
data=[ 1, 2, 3] ,[ 4, 7, 8], [ 13, 9, 10]
true1=[2,6,9]
for i in zip(*data,true1):
print(min([(abs(k - i[-1:][0]), k, i[-1:][0]) for k in i[:-1]])[1:])
Note that in last item [3,8,10]
8 is close to 9 :
output:
(1, 2)
(7, 6)
(8, 9)
Upvotes: 0
Reputation: 73480
You could just do this using map
and the zip(*...)
transpositioning idiom:
>>> lists = [[1, 2, 3], [ 4, 7, 8], [13, 9, 10]]
>>> lst = [2,6,9]
>>> list(map(takeClosest, lst, zip(*lists)))
# OR: list(map(takeClosest, Mynumber, zip(Mylist1, Mylist2, Mylist3)))
[1, 7, 8] # 9 is as close to 8 as it is to 10
This will apply your takeClosest
function to (2, [1, 4, 13])
, (6, [2, 7, 9])
, etc.
Upvotes: 1
Reputation: 1467
Here's a kind of ugly way to do it.
Mylist1= [ 1, 2, 3]
Mylist2= [ 4, 7, 8]
Mylist3= [ 13, 9, 10]
Mynumber=[2,6,9]
closest_values = []
for num in range(len(Mynumber)):
differences = {Mylist1[num]: abs(Mylist1[num]-Mynumber[num]),
Mylist2[num]: abs(Mylist2[num]-Mynumber[num]),
Mylist3[num] : abs(Mylist3[num]-Mynumber[num])}
closest_values.append(min(differences, key=differences.get))
print(closest_values)
#[1, 7, 8]
Upvotes: 0