Python: 我想找到列表中两个元素之间的最大差值
我需要找出一个列表中任意两个元素之间的最大差值。在列表 [1,2,3,4,5]
中,最大差值是 4(就是元素 1 和 5 之间的差)。
这个程序需要输出这两个元素的位置(0 和 4)以及它们的值(1 和 5)。
我只知道怎么找出相邻值之间的最大差值,但这样会有问题,因为最大差值可能出现在其他地方,比如在 [4,1,6,3,10,8]
这个列表中,最大差值是 1 和 10 之间的(位置 1 和 4)。有人能帮帮我吗?
7 个回答
这可以通过使用 max
和 min
结合 enumerate
来实现:
biggest_idx, biggest_value = max(enumerate(lst), key=lambda x: x[1])
smallest_idx, smallest_value = min(enumerate(lst), key=lambda x: x[1])
例如:
>>> lst = [1,2,3,4,5]
>>> biggest_idx, biggest_value = max(enumerate(lst), key=lambda x: x[1])
>>> smallest_idx, smallest_value = min(enumerate(lst), key=lambda x: x[1])
>>> print biggest_idx, biggest_value
4 5
>>> print smallest_idx, smallest_value
0 1
只需要把最小值减去最大值就可以了。这在Python中非常简单。有一种很酷的方法可以用itemgetter
来实现。如果你在列表中遍历每个项目,你可以同时找到最小值和最大值的索引和对应的值,但要在原始值上进行最小值和最大值的计算。就像这样:
>>> import operator
>>> values = [1, 2, 3, 4, 5]
>>>
>>> min_index, min_value = min(enumerate(values), key=operator.itemgetter(1))
>>> min_index, min_value
0, 1
>>> max_index, max_value = max(enumerate(values), key=operator.itemgetter(1))
4, 5
>>> difference = max_value - min_value
>>> difference
4
你可以先对列表进行排序,然后再找出最小值和最大值。同时,可以使用index()
来获取某个元素的位置:
L = [1, 2, 3, 4, 5]
temp = sorted(L) # sorted list
min = temp[0]
max = temp[-1] # index -1 will give the last element
测试:
print "min", min, L.index(min)
print "max", max, L.index(max)
print "difference", max - min
输出:
min 1 0
max 5 4
difference 4
在最简单的方法中,你会用两个嵌套的循环,这样可以确保每个元素都能和其他列表中的每个元素进行比较。因为你只需要检查每一对元素一次,所以每次内层循环可以从下一个索引开始:
lst = [1, 2, 3, 4, 5]
max_i, max_j = None, None # stores the indexes
max_d = -1 # stores the maximum distance we have seen so far
# iterate through all indexes of the list
for i in range(len(lst)):
# iterate through all indexes, but starting from the index `i+1`
for j in range(i + 1, len(lst)):
d = abs(lst[i] - lst[j])
if d > max_d:
# memorize everything if the distance is larger than what we know
max_i, max_j, max_d = i, j, abs(d)
print(max_i, max_j, max_d) # 0 4 4
用两个嵌套循环,这种方法效率并不是很高,但这确实是当你真的需要比较每个列表元素时的解决方案。在你寻找最大距离的情况下,正如其他人提到的,你只需要关注列表中最大的和最小的元素,这两个值都可以通过线性时间来找到。
正如你在上面的评论中提到的,似乎你只能使用for循环,所以我们可以通过自己在一次循环中找到最小值和最大值来提高效率:
# set the current maximum and minimum to the first index
max_i, min_i = 0, 0
# iterate the list from the second index
for i in range(1, len(lst)):
# check if we’re larger than the current maximum
if lst[i] > lst[max_i]:
max_i = i
# check if we’re smaller than the current minimum
if lst[i] < lst[min_i]:
min_i = i
distance = lst[max_i] - lst[min_i]
print(min_i, max_i, distance) # 0 0 4
这实际上和mgilson的答案做的事情是一样的。我们只是自己完成了内置函数max
和min
的工作,手动找到最小值和最大值。
你可以使用内置的函数 max
和 min
来找到列表中的最大值和最小值,然后再用列表的方法 index
来找到它们在列表中的位置。
numlist = [1, 2, 3, 4, 5]
max_val = max(numlist)
min_val = min(numlist)
max_pos = numlist.index(max_val)
min_pos = numlist.index(min_val)