使用 Python 3,我想按升序遍歷第一個列表中的項目,并在第二個列表中找到該項目的索引以將其存儲到第三個結果列表中。下面是一個工作示例:list1 = [53, 65, 67, 37, 14, 98, 122, 124, 183]list2 = [0, 14, 37, 53, 65, 67, 98, 122, 124, 183, 199]wanted_output = getWantedOutput(list1, list2)print(wanted_output)>>> [3, 4, 5, 2, 1, 6, 7, 8, 9]
3 回答

森林海
TA貢獻2011條經驗 獲得超2個贊
這種方法的可讀性不如其他給出的答案,但如果您的列表很長,它會更快。
wanted_output = []
for item in list1:
try:
wanted_output.append(list2.index(item))
except ValueError: # item not in list2
continue

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
長列表最有效的解決方案是預處理第二個列表并將其轉換為字典,其中列表項是鍵,它們的位置是值。然后在該字典中查找第一個列表中的元素:
positions = {item: pos for pos, item in enumerate(list2)}
[positions[item] for item in list1]
#[3, 4, 5, 2, 1, 6, 7, 8, 9]

阿波羅的戰車
TA貢獻1862條經驗 獲得超6個贊
list1 = [53, 65, 67, 37, 14, 98, 122, 124, 183]
list2 = [0, 14, 37, 53, 65, 67, 98, 122, 124, 183, 199]
[list2.index(x) for x in list1 if x in list2]
Output:
[3, 4, 5, 2, 1, 6, 7, 8, 9]
添加回答
舉報
0/150
提交
取消