[英]Python: I'm trying to find the maximum difference between two elements in a list
I need to find the maximum difference in a list between any two elements. 我需要在任何两个元素之间找到列表中的最大差异。 In list
[1,2,3,4,5]
the maximum difference is 4 (between elements 1 and 5) using for loops. 在列表
[1,2,3,4,5]
,使用for循环的最大差异为4(在元素1和5之间)。
This program needs to output the location of these two elements (0 and 4) and their values (1 and 5). 该程序需要输出这两个元素(0和4)的位置及其值(1和5)。
I can only figure out how to find the max difference between consecutive values, but this creates a problem if the maximum starts elsewhere, eg [4,1,6,3,10,8]
where the largest difference is between 1 and 10 (positions 1 and 4). 我只能弄清楚如何找到连续值之间的最大差异,但如果最大值从其他地方开始,这会产生问题,例如
[4,1,6,3,10,8]
,其中最大差异在1到10之间(位置1和4)。 Can someone help me? 有人能帮我吗?
You can use the built-in functions max
and min
to find the maximum and minimum values respectively and then use the list method index
to find their indices in the list. 您可以使用内置函数
max
和min
分别查找最大值和最小值,然后使用list方法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)
In the naive approach, you simply have two nested loops in that makes sure that each elements visits every other list element. 在天真的方法中,您只需要两个嵌套循环,以确保每个元素访问每个其他列表元素。 As you only need to check every pair once, it's enough to start the inner loop at the next index every time:
因为您只需要检查每对一次,所以每次在下一个索引处启动内部循环就足够了:
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
With two nested loops, this is of course not really efficient, but this is essentially the solution for when you really need to compare every list element with each other. 有两个嵌套循环,这当然不是很有效,但这实际上是当你真正需要将每个列表元素相互比较时的解决方案。 In your case of finding the maximum distance, as others pointed out, you only need to look at the largest and the smallest list item which can both be determined in linear time.
在您找到最大距离的情况下,正如其他人指出的那样,您只需要查看最大和最小的列表项,这两个列表项都可以在线性时间内确定。
As you said in a comment above, it seems that you are only allowed to use for loops, so we can still make it efficient, by doing the min/max finding ourself in linear time, by iterating only once: 正如你在上面的评论中所说的那样,似乎你只允许使用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
This essentially does the same as the answer by mgilson does. 这与mgilson的答案基本相同。 We just do the job of built-in functions
max
and min
ourselves and find the minimum and maximum manually. 我们只需要自己完成内置函数
max
和min
,并手动找到最小值和最大值。
You can sort the list first, then get the minimum and maximum values. 您可以先对列表进行排序 ,然后获取最小值和最大值。 Also, use
index()
to get the position of an element: 另外,使用
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
Test: 测试:
print "min", min, L.index(min)
print "max", max, L.index(max)
print "difference", max - min
Output: 输出:
min 1 0
max 5 4
difference 4
Just subtract the maximum value from the minimum value. 只需从最小值中减去最大值即可。 This is trivial in Python.
这在Python中是微不足道的。 A cool way to do this is with
itemgetter
. 一个很酷的方法是使用
itemgetter
。 You can find the min/max index and value at the same time if you enumerate the items in the list, but perform min/max on the original values of the list. 如果枚举列表中的项目,则可以同时找到最小/最大索引和值,但对列表的原始值执行最小值/最大值。 Like so:
像这样:
>>> 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
This can be accomplished using max
and min
+ enumerate
: 这可以使用
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])
eg: 例如:
>>> 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
min_i = 0
max_i = 0
for i in xrange(len(alist)):
if alist[i] < alist[min_i]:
min_i = i
if alist[i] > alist[max_i]:
max_i = i
print "min=%d, max=%d" % (alist[min_i], alist[max_i])
print "min index=%d, max index=%d", (min_i, max_i)
print "difference=%d" % (alist[min_i] - alist[max_i])
It can be as simple as ... 它可以像......一样简单
numlist=[4,1,6,3,10,8]
print('min value index : ' , numlist.index(min(numlist)))
print('max value index : ' , numlist.index(max(numlist)))
print('Max Difference : ',max(numlist)-min(numlist))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.