Skip to main content
 首页 » 编程设计

python之在数字列表中找到最接近的录制速度 [python]

2025年05月04日20yxwkf

我需要知道如何遍历列表并找到最接近限速的速度。所以几乎遍历速度列表,每次都查看差异。

我目前拥有的:

def find_nearest_speed(recorded_speeds, speed_limit): 
"""Finds the closest recorded speed when compared to the speed limit.""" 
closest = abs(speed_data[0] - speed_limit) 
for current_element in speed_data: 
    speed_difference = abs(current_element - speed_limit) 
    if speed_difference < abs(closest - speed_limit): 
        closest = current_element 
        return closest 
 
max_speed = 30  
speed_data = [24, 25, 27, 28, 31, 35]            
closest_speed = (find_nearest_speed(speed_data, max_speed)) 
print("The closest recorded speed was {} Km/h.".format(closest_speed)) 

我得到的:

 The closest recorded speed was 24 Km/h. 

我应该得到什么:

 The closest recorded speed was 31 Km/h. 

请您参考如下方法:

你可以使用 min :

max_speed = 30 
speed_data = [24, 25, 27, 28, 31, 35] 
closest_speed = min(speed_data, key=lambda x: abs(x - max_speed)) 
print("The closest recorded speed was {} Km/h.".format(closest_speed)) 

输出

The closest recorded speed was 31 Km/h.