訪問 Python 中給定的索引列表中的所有元素


可以使用 [] 括號和索引號訪問列表中的單個元素。但當我們需要訪問某些索引時無法應用此方法。我們需要用以下方法來解決此問題。

使用兩個列表

此方法中,我們會將原始列表與索引作為另一個列表。然後使用 for 迴圈來遍歷索引並將這些值提供給主列表以檢索值。

示例

 即時演示

given_list = ["Mon","Tue","Wed","Thu","Fri"]
index_list = [1,3,4]

# printing the lists
print("Given list : " + str(given_list))
print("List of Indices : " + str(index_list))

# use list comprehension
res = [given_list[n] for n in index_list]

# Get the result
print("Result list : " + str(res))

輸出

執行以上程式碼將得到以下結果 −

Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
List of Indices : [0, 1, 2, 3, 4]
Result list : ['Tue', 'Thu', 'Fri']

使用 map 和 getitem

除了使用上面的 for 迴圈外,還可使用 map 和 getitem 方法獲得相同的結果。

示例

 即時演示

given_list = ["Mon","Tue","Wed","Thu","Fri"]
index_list = [1, 3,4]

# printing the lists
print("Given list : " + str(given_list))
print("List of Indices : " + str(index_list))

# use list comprehension
res = list(map(given_list.__getitem__,index_list))

# Get the result
print("Result list : " + str(res))

輸出

執行以上程式碼將得到以下結果 −

Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
List of Indices : [1, 3, 4]
Result list : ['Tue', 'Thu', 'Fri']

更新日期:03-3 月-2020

273 次瀏覽

開啟您的 職業生涯

完成課程並獲得認證

開始
廣告