我需要知道如何遍历列表并找到最接近限速的速度。如此反复遍历速度列表,每次都看一下差异。
到目前为止我所拥有的:
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.
答案 0 :(得分:4)
您可以使用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.
答案 1 :(得分:1)
这是您应该拥有的:
def find_nearest_speed(recorded_speeds, speed_limit):
"""Finds the closest recorded speed when compared to the speed limit."""
closest = float('inf')
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 if len(recorded_speeds) > 0 else None
唯一的变化是最初closest = float('inf')
答案 2 :(得分:0)
如果在return
语句“内部”使用if
语句,则只要满足条件speed_difference < abs(closest - speed_limit)
为true
,它将立即返回您的代码用于列表的第一个元素。
因此,您需要在return
语句之前删除缩进,以便它在循环结束之前返回结果。
另一个要注意的是,语句closest = abs(speed_data[0] - speed_limit)
是错误的,因为您要为closest
变量分配list元素和speed_limit
之间的差异,但是要查看函数代码您应该为它分配一个列表元素:closest = speed_data[0]
。
def find_nearest_speed(recorded_speeds, speed_limit):
"""Finds the closest recorded speed when compared to the speed limit."""
closest = speed_data[0] # Sets the closest as the list's first element
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))