Python - 在列表中查找值索引的方法
pythonserver side programmingprogramming更新于 2025/9/17 7:40:17
通常,我们需要找到特定值所在的索引。有很多方法可以实现这一点,使用 index() 等。但有时需要找到特定值的所有索引,以防它在列表中多次出现。
示例
# 使用 filter()
# 初始化列表
test_list = [1, 3, 4, 3, 6, 7]
# 打印初始列表
print ("Original list : " + str(test_list))
# 使用 filter()
# 查找 3 的索引
res_list = list(filter(lambda x: test_list[x] == 3, range(len(test_list))))
# 打印结果列表
print ("新索引列表:" + str(res_list))
# 使用 enumerate()
# 初始化列表
test_list = [1, 3, 4, 3, 6, 7]
# 打印初始列表
print ("原始列表:" + str(test_list))
# 使用 enumerate()
# 查找 3 的索引
res_list = [i for i, value in enumerate(test_list) if value == 3]
# 打印结果列表
print ("新索引列表:" + str(res_list))
# 使用列表推导式
# 初始化列表
test_list = [1, 3, 4, 3, 6, 7]
# 打印初始列表
print ("Original list : " + str(test_list))
# 使用列表推导式
# 查找 3 的索引
res_list = [i for i in range(len(test_list)) if test_list[i] == 3]
# 打印结果列表
print ("New indices list : " + str(res_list))
# 使用简单方法
# 初始化列表
test_list = [1, 3, 4, 3, 6, 7]
# 打印初始列表
print ("Original list : " + str(test_list))
# 使用简单方法
# 查找 3 的索引
res_list = []
for i in range(0, len(test_list)) :
if test_list[i] == 3 :
res_list.append(i)
# 打印结果列表
print ("新索引列表:" + str(res_list))
输出
原始列表:[1, 3, 4, 3, 6, 7] 新索引列表:[1, 3] 原始列表:[1, 3, 4, 3, 6, 7] 新索引列表:[1, 3] 原始列表:[1, 3, 4, 3, 6, 7] 新索引列表:[1, 3] 原始列表:[1, 3, 4, 3, 6, 7] 新索引列表:[1, 3]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

