Python 为子列表编制索引
本教程中,我们将编写一个从列表中查找子列表元素索引的程序。我们来看一个示例,以便清楚地理解它。
输入
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
输出
Index of 7:- 2 Index of 5:- 1 Index of 3:- 0
我们来了解一个简单、最常见的方法来解决这个问题。请按照给定的步骤进行操作。
- 初始化列表。
- 使用索引迭代列表。
- 迭代子列表并检查要查找索引的元素。
- 如果我们找到了这个元素,则打印并进行中断。
示例
# initializing the lit
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# function to find the index
def index(element):
# initializing a flag for tracking the element
is_found = False
# iterating over the list
for i in range(len(nested_list)):
# iterating over the sub list
for j in range(len(nested_list[i])):
# cheking for the element
if nested_list[i][j] == element:
# printing the sub list index that contains the element
print(f'Index of {element}: {i}')
# changing the flag to True
is_found = True
# breaking the inner loop
break
# breaking the outer loop
if is_found:
break
# checking whether the element is found or not
if not is_found:
# printing the element not found message
print("Element is not present in the list")
index(7)
index(5)
index(3)输出
如果运行上面的代码,则会得到以下结果。
Index of 7: 2 Index of 5: 1 Index of 3: 0
结论
如果你对教程有任何疑问,请在评论区中提及。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
Javascript
PHP