在本教程中,我们将编写一个程序,该程序从列表中查找子列表元素的索引。让我们看一个例子来清楚地理解它。

输入列表nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

输出结果Index of 7:- 2

Index of 5:- 1

Index of 3:- 0

让我们看看解决给定问题的最简单,最常见的方法。按照给定的步骤解决它。初始化列表。

使用索引遍历列表。

遍历子列表并检查要查找索引的元素。

如果找到了元素,则打印并中断循环

示例#初始化列表

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