Python – 在元組列表中根據第二個元素查詢第一個元素


元組列表定義了Python的兩種不同資料型別,分別表示靜態和動態特性。在字典中,我們可以使用元組建立鍵,而列表不能用作鍵。在Python中,我們有一些內建函式,如next()、items()、index()、lambda和min(),可以用來在元組列表中根據第二個元素查詢第一個元素。當第二個元素作為識別所需元組的關鍵資訊時,就會出現這種情況。

讓我們來看一個例子

給定的元組列表:

my_tup = [("India", 35), ("Indonesia", 12), ("London", 31), ("Germany", 20)])

搜尋列表中元組中存在的特定值:

search_value = 31

輸出

Germany

解釋

名為my_tup的變數儲存包含字串和整數的元組列表。根據給定的問題陳述,將整數值31設定為變數search_value。最終輸出為Germany

語法

以下語法在示例中使用:

next()

next()是一個內建函式,用於迭代迭代器中的下一個專案。

items()

items()是Python中的一個內建方法,它返回一個檢視物件,其中包含鍵值對。

index()

index()是Python中的一個內建函式,可用於從列表中搜索元素並返回元素的位置。

lambda

Python中的這個lambda函式稱為匿名函式。當需要函式物件時可以使用它。

min()

內建函式min返回可迭代物件中的最小項。這也可以用於查詢兩個引數之間的最小元素。

使用for迴圈

在下面的示例中,程式使用for迴圈迭代元組。如果在給定的輸入元組列表中找到第二個元素,則返回相應的第一個元素。否則,返回None並顯示結果。

示例

def find_first_element(tuples, second_value):
    for first, second in tuples:
        if second == second_value:
            return first
    return None  # Return None if the second value is not found

# create the tuple list
my_tuples = [("amar", 3), ("akbar", 2), ("anthony", 31)]
second_value = 31
result = find_first_element(my_tuples, second_value)
print(result)

輸出

 anthony

使用next()

在下面的示例中,程式使用遞迴函式,這意味著它呼叫自身。接下來,它將使用內建函式next(),根據給定的輸入迭代下一個專案。程式還提到了第二個元素的值,這將有助於找到列表中元組的第一個元素。

示例

def find_first_element(tuples, second_value):
    result = next((first for first, second in tuples if second == second_value), None)
    return result

# create the tuple list
my_tuples = [("String", 3), ("letter", 2), ("word", 3)]
second_value = 2
result = find_first_element(my_tuples, second_value)
print(result)

輸出

 letter

使用dict()和next()函式

在下面的示例中,程式使用內建函式dict()將元組列表的值轉換為字典,這將用於理解技術來解決元組列表中根據第二個元素查詢第一個元素的問題,並顯示結果。

示例

def find_first_element(tuples, second_value):
    dict_tuples = dict(tuples)
    result = next((key for key, value in dict_tuples.items() if value == second_value), None)
    return result

# create the tuple list
my_tuples = [("Manish", 3), ("Ram", 2), ("shyam", 3), ("Deepak", 4)]
second_value = 3
result = find_first_element(my_tuples, second_value)
print(result)

輸出

 Manish

使用lambda函式和min()函式

在下面的示例中,程式使用內建函式lambda根據元組列表中的第二個元素計算第一個元素的條件。

示例

def find_first_element(tuples, second_value):
    result = min(tuples, key=lambda x: (x[1] != second_value, tuples.index(x)))[0]
    return result
# create the tuple list
my_tuples = [("pen", 1), ("pencil", 2), ("notebook", 3), ("eraser", 4)]
second_value = 4
result = find_first_element(my_tuples, second_value)
print(result)

輸出

 eraser

結論

該程式涉及對給定元組列表的迭代,透過提及元組的第二個值進行比較,以返回第一個元組並滿足特定條件和操作。在現實世界中有一些應用,例如排序和過濾、資料處理、資料分析和統計等。

更新於:2023年8月16日

瀏覽量:395

開啟你的職業生涯

完成課程後獲得認證

開始學習
廣告