0

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]
    """
  • So what do you want the output to be? – user2390182 Dec 11 '17 at 18:21
  • So you want to compare the first item in `Mynumber` to `Mylist1`, second item in `Mynumber` to `Mylist2` etc? – MCBama Dec 11 '17 at 18:22
  • Hi MCBama, no, I want to compare first item in Mynumber to three first numbers in Mylists, second item in Mynumber to three second numbers in Mylists, and third item in Mynumber to three third numbers in Mylists. My output should be ( 1,7,8) – user9059368 Dec 11 '17 at 18:29
  • @user9059368 does the below answers answer your question? – Amit Tripathi Dec 11 '17 at 20:00

3 Answers3

1

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.

user2390182
  • 72,016
  • 6
  • 67
  • 89
  • thank you so much for your valuable responses.. I appreciate it.. all the answers given here are correct.. but unfortunately I can not put a tick for all of them, when I put a tick for 2, one will disappear. Thank you so much every one – user9059368 Dec 13 '17 at 00:38
0

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]
Dave Rosenman
  • 1,252
  • 9
  • 13
0

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)
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88