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

结论

如果你对教程有任何疑问,请在评论区中提及。

更新于: 07-Jul-2020

2K+ 查看次数

开启你的 事业

完成课程以获得认证

开始
广告
© . All rights reserved.