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]
热门推荐
10 学弟英语高考祝福语简短
11 侄儿高考试祝福语简短
12 预祝中秋简短的祝福语
13 新娘生孩子祝福语简短
14 小孩生日送花祝福语简短
15 中秋骚气祝福语简短情人
16 情侣520的祝福语简短
17 简短微信祝福语大全
18 给妹妹婚礼祝福语简短