Python程式:獲取一個列表中每個元素在另一個列表中的索引


當需要獲取一個列表中每個元素在另一個列表中的索引時,可以使用簡單的迭代、enumerate屬性以及`setdefault`方法。

它也使用列表推導式,並使用`get`方法。

示例

以下是演示:

my_list = [14, 52, 23, 47, 18, 23, 12, 54, 43, 22, 28, 13]

print("The list is :")
print(my_list)

my_list_2 = [17, 52, 13]
print("The second list is :")
print(my_list_2)

element_indices = dict()
for index, value in enumerate(my_list):
   element_indices.setdefault(value, []).append(index)

my_result = [element_indices.get(index, [None]) for index in my_list_2]

print("The result is :")
print(my_result)

輸出

The list is :
[14, 52, 23, 47, 18, 23, 12, 54, 43, 22, 28, 13]
The second list is :
[17, 52, 13]
The result is :
[[None], [1], [11]]

解釋

  • 定義一個整數列表並在控制檯上顯示。

  • 定義另一個整數列表並在控制檯上顯示。

  • 建立一個空字典。

  • 使用`enumerate`迭代第一個列表。

  • 使用`setdefault`方法為元素賦值。

  • 將其新增到空字典中。

  • 使用列表推導式迭代元素,並使用`get`方法獲取第二個列表中元素的索引值。

  • 將其儲存在一個列表中並賦值給一個變數。

  • 將此列表作為輸出顯示在控制檯上。

更新於:2021年9月8日

瀏覽量:179

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.