इस ट्यूटोरियल में, हम एक प्रोग्राम लिखने जा रहे हैं जो सूची से एक सबलिस्ट एलिमेंट का इंडेक्स ढूंढता है। आइए इसे स्पष्ट रूप से समझने के लिए एक उदाहरण देखें।
इनपुट
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
निष्कर्ष
यदि आपके पास ट्यूटोरियल के संबंध में कोई प्रश्न हैं, तो उनका टिप्पणी अनुभाग में उल्लेख करें