查找3个列表的最接近值

时间:2017-12-11 18:19:56

标签: python list

这是我的代码,用于从给定数字(Mynumber)获取最接近的值  列表(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

现在我有3个清单[1,2,3],[4,7,8],[13,9,10] 我想比较它们的第一项,第二项和第三项 list,[2,6,9],如果我比较每个列表中的第1项,如果[1,4,13],1是最接近2,如果我比较每个列表中的第2项,则为[2, 7,9],7是最接近6,如果我比较每个列表中的第3项,[3,8,10]中,10是最接近9 有谁知道怎么做?任何建议都将不胜感激

    """
    Mylist1= [ 1, 2, 3]
    Mylist2= [ 4, 7, 8]
    Mylist3= [ 13, 9, 10]

    Mynumber=[2,6,9]
    """

3 个答案:

答案 0 :(得分:1)

您可以使用mapzip(*...) 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

这会将您的takeClosest功能应用于(2, [1, 4, 13])(6, [2, 7, 9])等。

答案 1 :(得分:0)

这是一种难看的方式。

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]

答案 2 :(得分:0)

您可以尝试这样的事情:

var tips = 5;
var devs = 20;
var donation = 75;

var setTips = function(newValue) {
  tips = newValue;
  var sum = devs + donation;
  var devShare = devs / sum; // the share devs gets between devs and donation
  var donationShare = 1 - devShare; // or could calculate as donation / sum
  
  devs = (100 - tips) * devShare; // the remaining times it's share ratio
  donation = (100 - tips) * donationShare; // the remaining times it's share ratio
};

// test it out
setTips(50);
console.log(tips, devs, donation);

请注意,在最后一项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:]) 中,8接近9:

输出:

[3,8,10]