Python - 查詢列表中值的索引的方法


通常,我們需要找出特定值位於其中的索引。有很多方法可以實現這一點,使用 index() 等。但是在列表中特定值有多次出現的情況下,有時需要找出所有這些值的索引。

示例

 即時演示

# using filter()
# initializing list
test_list = [1, 3, 4, 3, 6, 7]
# printing initial list
print ("Original list : " + str(test_list))
# using filter()
# to find indices for 3
res_list = list(filter(lambda x: test_list[x] == 3, range(len(test_list))))        
# printing resultant list
print ("New indices list : " + str(res_list))
# using enumerate()
# initializing list
test_list = [1, 3, 4, 3, 6, 7]
# printing initial list
print ("Original list : " + str(test_list))  
# using enumerate()
# to find indices for 3
res_list = [i for i, value in enumerate(test_list) if value == 3]        
# printing resultant list
print ("New indices list : " + str(res_list))
# using list comprehension
# initializing list
test_list = [1, 3, 4, 3, 6, 7]  
# printing initial list
print ("Original list : " + str(test_list))  
# using list comprehension
# to find indices for 3
res_list = [i for i in range(len(test_list)) if test_list[i] == 3]          
# printing resultant list
print ("New indices list : " + str(res_list))
# using naive method  
# initializing list
test_list = [1, 3, 4, 3, 6, 7]  
# printing initial list
print ("Original list : " + str(test_list))
# using naive method
# to find indices for 3
res_list = []
for i in range(0, len(test_list)) :
   if test_list[i] == 3 :
      res_list.append(i)
# printing resultant list
print ("New indices list : " + str(res_list))

輸出

Original list : [1, 3, 4, 3, 6, 7]
New indices list : [1, 3]
Original list : [1, 3, 4, 3, 6, 7]
New indices list : [1, 3]
Original list : [1, 3, 4, 3, 6, 7]
New indices list : [1, 3]
Original list : [1, 3, 4, 3, 6, 7]
New indices list : [1, 3]

更新於:06-8-2020

148 次瀏覽

開啟你的職業

完成課程以獲得認證

開始吧
廣告