python訪問列表不連續的多個元素
代碼
python訪問列表元素可以根據單個索引訪問,可以使用切片訪問連續的元素,但是當想訪問列表的多個不連續的元素時,可以建立一個索引列表,然后使用如下的列表推導式。
list_1 = [1,2,3,4,5]
list_2 = [2,4]
list_3 = [list_1[i] for i in list_2]
或者使用 .index()函數
list_1 = [1,2,3,4,5]
list_2 = [2,4]
list_3 = [x for x in list_1 if list_1.index(x) in list_2]