Python 索引子列表
pythonserver side programmingprogramming更新于 2025/7/23 8:44:17
在本教程中,我们将编写一个程序,从列表中查找子列表元素的索引。让我们看一个例子来清楚地理解它。
输入
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
输出
Index of 7:- 2 Index of 5:- 1 Index of 3:- 0
让我们看看解决给定问题的最简单和最常见的方法。按照给定的步骤解决它。
- 初始化列表。
- 使用索引遍历列表。
- 遍历子列表并检查要查找索引的元素。
- 如果我们找到元素,则打印并打破它
示例
# 初始化 lit
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# 查找索引的函数
def index(element):
# 初始化用于跟踪元素的标志
is_found = False
# 遍历列表
for i in range(len(nested_list)):
# 遍历子列表
for j in range(len(nested_list[i])):
# 检查元素
if nested_list[i][j] == element:
# 打印包含元素的子列表索引
print(f'Index of {element}: {i}')
# 将标志更改为 True
is_found = True
# 打破内循环
break
# 打破外循环
if is_found:
break
# 检查元素是否找到
if not is_found:
# 打印元素未找到消息
print("元素不在列表中")
index(7)
index(5)
index(3)
输出
如果您运行上述代码,那么您将获得以下结果。
Index of 7: 2 Index of 5: 1 Index of 3: 0
结论
如果您对本教程有任何疑问,请在评论部分中提及
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

