在列表中從 Python 元組訪問第 n 個元素


Python 列表可以將元組作為其元素。在本文中,我們將探討如何訪問作為給定元組元素的元組中的每個第 n 個元素。

使用索引

我們可以設計一個 for 迴圈來訪問列表中的元素,並對其應用第 n 個索引的 in 子句。然後,我們將結果儲存到新列表中。

示例

 實際演示

Alist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]

#Given list
print("Given list: ",Alist)

# Use index
res = [x[1] for x in Alist]

print("The 1 st element form each tuple in the list: \n",res)

輸出

執行上面的程式碼將得到以下結果:

Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]
The 1 st element form each tuple in the list:
['3 pm', '12pm', '9 am', '6 am']

使用 itemgetter

operator 模組中的 itegetter 函式可以從給定的可迭代物件中獲取每個專案,直到搜尋到該可迭代物件的結尾。在這個程式中,我們搜尋給定列表中的索引位置 2,並應用一個map函式,以便對itegetter函式結果中的每個結果反覆應用相同的函式。最後,我們將結果儲存為一個列表。

示例

 實際演示

from operator import itemgetter

Alist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]

#Given list
print("Given list: ",Alist)

# Use itemgetter
res = list(map(itemgetter(2), Alist))

print("The 1 st element form each tuple in the list: \n",res)

輸出

執行上面的程式碼將得到以下結果:

Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]
The 1 st element form each tuple in the list:
[10, 8, 8, 5]

更新於:2020-05-13

826 次瀏覽

啟動你的 職業生涯

完成課程以獲得認證

開始吧
廣告
© . All rights reserved.