使用 Python 查詢元素之間的最大距離


簡介

列表資料結構處理不同資料型別(如整數、浮點數或字串)的元素。元素需要用逗號分隔並在方括號內定義。Python 語言主要由不同的資料結構組成,其中列表資料結構是最常用的。列表可以儲存不同資料型別的元素,並且一旦它們被賦值,就不能更改。在本文中,我們將找到元素之間的最大距離。

元素之間的最大距離

列表中的元素使用索引值識別,並根據此索引值計算最大距離。讓我們以列表資料結構為例,

List1 = [1, 3, 5, 1, 5, 7, 8]

對於位於最大距離處的相同元素找到距離,在上述情況下,索引 0 處的元素為 1,相同元素位於索引值為 3 的位置。因此,元素之間的最大距離為 3。

方法

方法 1:使用 numpy 模組

方法 2:使用迭代方法

方法 1:使用 Numpy 模組在 Python 中查詢元素之間的最大距離

列表用七個整數元素宣告,距離值使用 numpy 計算。

演算法

步驟 1:使用模組初始化輸入列表,其中包含七個整數資料型別。

步驟 2:名為“maximum_distance”的變數賦值為零。

步驟 3:藉助唯一函式,透過遍歷列表的每個元素並將它們儲存在變數中,找到列表中的唯一元素。

步驟 4:將名為“maximum_distance”的變數設定為零。

步驟 5:查詢距離的方法需要元素的位置,根據該位置可以計算元素的最大距離。

步驟 6:透過取輸入列表的 max 和 min 函式之間的差值來計算距離。

步驟 7:列印輸出。

示例

#import the module
import numpy as np
#initializing the list with the same elements at different index values
List1 = [1, 3, 5, 2, 1, 7, 8]
#function is used to get the specific element of the list
val = np.unique(List1)
#Storing the element value as ‘0’
maximum_dis = 0
#for loop will iterate through the list
for uni in val:
#To get the distance, the where the function is used to get the index value
	location = np.where(np.array(List1) == uni)[0]
#The distance returns the difference between the max and min index value
	dis = np.max(location) - np.min(location)
#When the ‘dis’ is greater than the maximum distance, the value is returned.
	if dis > maximum_dis:
		maximum_dis = dis
#Print functions return the final value
print("Maximum distance obtained in the given list:", maximum_dis)

輸出

Maximum distance obtained in the given list: 4

方法 2:使用迭代方法查詢元素之間最大距離的 Python 程式

在這種情況下,使用列表資料結構初始化一組整數元素的輸入,併為了找到元素之間的最大距離,初始化具有不同索引的相同值的元素,並計算最大距離。

演算法

步驟 1:初始化列表。

步驟 2:名為“maximum_distance”的變數賦值為零。

步驟 3:使用巢狀 for 迴圈,for 迴圈將遍歷給定列表以獲取列表的長度。

步驟 4:接下來,第二個 for 迴圈將遍歷每個元素以查詢列表元素之間的最大距離。

步驟 5:abs() 函式將返回索引 (a,b) 的絕對值。

步驟 6:然後找到位於最大距離處的最終元素,並返回元素的距離。

示例

def element_max(gt):
    nonduplicate_elems = gt
    mt = 0
    for x in nonduplicate_elems:
        nd = [m for m, r in enumerate(gt) if r == x]
        t = max(nd) - min(nd)
        if t > mt:
            mt = t
    return mt
gt = [4, 9, 6, 2, 9, 1]
mt = element_max(gt)
print("The longest distance is:", mt)

輸出

The longest distance is: 3

結論

Python 列表可以包含所有形式的元素,如正值和負值。已經解釋了不同的方法來處理 abs() - 絕對函式、獲取唯一值的唯一方法,以及最後獲取元素索引位置的 where 函式。這些方法將幫助程式設計師在定義的值中找到元素之間的最大距離。

更新於: 2023-08-07

505 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告