简体   繁体   English

Python:我试图找到列表中两个元素之间的最大差异

[英]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. 您可以使用内置函数maxmin分别查找最大值和最小值,然后使用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. 我们只需要自己完成内置函数maxmin ,并手动找到最小值和最大值。

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 : 这可以使用maxmin + 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.

相关问题 查找两个列表之间具有最大差异的元素索引 - Find elements' indices with maximum difference between two lists 用python查找列表的3个最大元素 - Find 3 maximum elements of list with python 快速查找 Python 列表中 i 之前所有元素最大值的方法 - Fast way to find the maximum of all elements before i in a list in Python 如何在 Python 的列表中的两个元素之间找到缺失的元素? - How to find missing elements between two elements in a list in Python? 如何在Python的列表中重复查找两个元素之间的所有元素? - How to find all elements between two elements repeatedly in a list in Python? 这两个 python 异步代码示例有什么区别? 我试图理解为什么使用 aiohttp 而不是请求 - what is the difference between these two python asyncio code samples? i'm trying to understand why aiohttp is used rather than requests 如何在列表中找到两个元素的最大乘积? - How to find the maximum product of two elements in a list? 对列表中的元素求和并在Python中找到最大值 - Sum elements in a list of lists and find maximum in Python 我试图找出哪一天最大压力和最小压力之间的差异最大, - I am trying to find which day has the highest difference between maximum_pressure and minimum_pressure, Python 2.7-如何找到以秒/微秒为单位的两个datetime.fromtimestamp(ts).strftime(&#39;%Y-%m-%d%H:%M:%S.%f&#39;)时间戳之间的差异? - Python 2.7 - how can I find the difference between two datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S.%f') timestamps in seconds/microseconds?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM