返回列表中最接近的值

时间:2014-08-27 17:15:00

标签: python

正在输出的列表如下。我想要做的是找到第二列中数字的最接近的值加上步长。我该怎么做呢?我尝试过使用min函数,但它不可迭代。

stepsize = .5
return closest(column[1] + stepsize)

(72817, 10.009872745252624, 40.999890710175876, 9.73)
(103394, 10.044319950550072, 11.450070211613395, 8.1)
(52251, 10.047512210212679, 73.31363177934391, 9.75)
(98118, 10.558521350586966, 24.665802379879878, 9.13)
(101401, 10.595011636219427, 17.691450116195412, 8.34)
(90376, 10.718434008267023, 32.37843662097162, 9.24)
(53624, 10.78156459297739, 65.73007957579946, 8.43)
(99855, 10.960898039784297, 20.83812851138556, 9.05)
(91937, 10.999664485957146, 31.048708072900475, 9.04)
(97166, 11.049670008406684, 25.46563972962055, 9.92)

所以应该返回10.558521 ...此列表会持续很长时间,因此步长会有所不同。

2 个答案:

答案 0 :(得分:4)

使用zip获取第一列,然后按每个元素的abs差异排序x + .5 -您希望它最接近的数字:

col = (zip(*l))[1] # l is your list of tuples

print sorted(col,key=lambda x: abs(x + 0.5 - 10.6))`
[10.047512210212679, 10.044319950550072, 10.009872745252624,10.558521350586966,10.595011636219427, 10.718434008267023, 10.78156459297739, 10.960898039784297, 10.999664485957146, 11.049670008406684]

sorted(col,key=lambda x: abs(x + 0.5 - 10.6))[0]将是最接近的

把它放在一个函数中:

def closest(l,step,val):
    col = (zip(*l))[1]
    return  sorted(col,key=lambda x: abs(x + step - val))[0]

答案 1 :(得分:0)

stepsize = 0.5
grid = [(72817, 10.009872745252624, 40.999890710175876, 9.73),
        (103394, 10.044319950550072, 11.450070211613395, 8.1),
        (52251, 10.047512210212679, 73.31363177934391, 9.75),
        (98118, 10.558521350586966, 24.665802379879878, 9.13),
        (101401, 10.595011636219427, 17.691450116195412, 8.34),
        (90376, 10.718434008267023, 32.37843662097162, 9.24),
        (53624, 10.78156459297739, 65.73007957579946, 8.43),
        (99855, 10.960898039784297, 20.83812851138556, 9.05),
        (91937, 10.999664485957146, 31.048708072900475, 9.04),
        (97166, 11.049670008406684, 25.46563972962055, 9.92)]

def closest(value, data):
    """Returns the closest element in data to the value passed"""
    return min(data, key=lambda x: abs(x-value))

results = [(row[1], closest(row[1]+stepsize, map(lambda x: x[1], grid))) for row in grid]
# or simplified using Padraic's zip method to grab the relevant column:
## data = (zip(*grid))[1]
## results = [(datum, closest(datum+stepsize, data)) for datum in data]

结果:

results = [(10.009872745252624, 10.558521350586966),
           (10.044319950550072, 10.558521350586966),
           (10.047512210212679, 10.558521350586966),
           (10.558521350586966, 11.049670008406684),
           (10.595011636219427, 11.049670008406684),
           (10.718434008267023, 11.049670008406684),
           (10.78156459297739, 11.049670008406684),
           (10.960898039784297, 11.049670008406684),
           (10.999664485957146, 11.049670008406684),
           (11.049670008406684, 11.049670008406684)]