簡體   English   中英

Python:我試圖找到列表中兩個元素之間的最大差異

[英]Python: I'm trying to find the maximum difference between two elements in a list

我需要在任何兩個元素之間找到列表中的最大差異。 在列表[1,2,3,4,5] ,使用for循環的最大差異為4(在元素1和5之間)。

該程序需要輸出這兩個元素(0和4)的位置及其值(1和5)。

我只能弄清楚如何找到連續值之間的最大差異,但如果最大值從其他地方開始,這會產生問題,例如[4,1,6,3,10,8] ,其中最大差異在1到10之間(位置1和4)。 有人能幫我嗎?

您可以使用內置函數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)

在天真的方法中,您只需要兩個嵌套循環,以確保每個元素訪問每個其他列表元素。 因為您只需要檢查每對一次,所以每次在下一個索引處啟動內部循環就足夠了:

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的答案基本相同。 我們只需要自己完成內置函數maxmin ,並手動找到最小值和最大值。

您可以先列表進行排序 ,然后獲取最小值和最大值。 另外,使用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

只需從最小值中減去最大值即可。 這在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

這可以使用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])

例如:

>>> 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])

它可以像......一樣簡單

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM