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