2014-08-27 179 views
0

正在輸出的列表如下。我想要做的是找到第二列中的數字最接近的值加上一個步長。我會如何去做這件事?我曾嘗試使用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 ...這個列表會持續很長時間,所以步長會有所不同。

+0

怎麼會加入0.5有什麼區別,如果你把它添加到所有的人? – 2014-08-27 17:16:00

+0

我不想將它添加到所有這些,我想找到第一個元素+ stepsize的最接近的值,然後對於下一個它將找到最接近該數字+ stepize再次。對不起,如果我沒有說清楚 – 2014-08-27 17:20:51

回答

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)] 
4

排序每個元素的abs差得到的只是使用zip然後第一列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]