给定l = [ [3,4,5], [30,40,50], [300,400,500] ]
和数字45
foo(l, 45)
应返回[30,40,50],因为它的平均值最接近45。
写这样一个函数“foo”的好方法是什么?
编辑:
这是我的代码..(尚未测试)
def _avg(l):
return reduce(lambda x,y: x+y, l)/len(l)
def foo(clusters, point):
return min(clusters, key=lambda x: abs( _avg(x) - point) )
答案 0 :(得分:1)
查找生成min
值的生成器表达式的abs(sublist_average - target_average)
。
l = [[3,4,5],[30,40,50],[300,400,500]]
avg = 45
result = min(((i,abs(sum(x)/len(x)-avg)) for i,x in enumerate(l)),key=lambda x:x[1])
#result = (1, 5.0)
print('the minimum delta, found at index {}, is {}'.format(*result))
#the minimum delta, found at index 1, is 5.0
答案 1 :(得分:0)
你怎么在纸上做这个?你首先要计算第一个的平均值,取差值,然后保存到目前为止最小距离的索引。最简单的解决方案可能是最好,最易理解的解决方案。
答案 2 :(得分:-1)
写得非常冗长......
import sys
def closest_average_to_num (list_of_lists, num):
closest_list = []
lowest_diff = sys.maxint
for list_of_interest in list_of_lists:
avg = sum(list_of_interest) / float(len(list_of_interest))
if (lowest_diff > abs(avg - num)):
lowest_diff = abs(avg - num)
closest_list = list_of_interest
return closest_list
示例输出:
>>> closest_average_to_num ([ [3,4,5], [30,40,50], [300,400,500] ], 45) [30, 40, 50]