问题的提出
- 给出一个列表
**lst**,以及 - 给出一个元素
**x**.
如何对 查找行和列的索引的元素x在列表的列表中的位置 **lst**?
如果该元素在列表中没有出现,返回值应该是元组 (-1, -1) 。如果该元素存在多次,返回值应该是第一次出现的(row, column) 索引。
下面是三个例子,展示了你的程序在三种重要情况下应该如何工作。
例子1:元素存在
Input:
例2: 元素不存在
Input:
例三:元素多次出现
Input:
接下来让我们深入了解一下解决方案吧
方法1:基本的Python For Loop & enumerate()
最简单和最Pythonic的方法是使用一个嵌套的for循环和内置的 [enumerate()](https://blog.finxter.com/python-enumerate/ "Python enumerate() — A Simple Illustrated Guide with Video")函数来同时遍历元素和索引。
下面是代码的解决方案。
def find_element(x, lst):
for i, row in enumerate(lst):
for j, element in enumerate(row):
if element == x:
return (i, j)
return (-1, -1)
- 外部 for 循环使用
enumerate()遍历内部列表和它们的 "行 "索引。如果你需要复习enumerate,请查看我 在Finxter博客上的深度教程,并观看本节末尾的讲解视频。 - 内循环遍历给定内列表中的每个元素,以及它的 "列 "索引。
- 一旦找到该元素,就返回行和列索引的元组
(i, j)。
让我们针对它运行我们的三个测试案例吧!
# Test Case 1: Element Exists
lst = [[1, 2, 3],
[4, 5, 6]]
x = 5
print(find_element(x, lst))
# Test Case 2: Element Doesn't Exist
lst = [[1, 2, 3],
[4, 5, 6]]
x = 0
print(find_element(x, lst))
# Test Case 3: Element Exists Multiple Times
lst = [['Alice', 'Bob'],
['Carl', 'Dave', 'Emil'],
['Emil', 'Emil']]
x = 'Emil'
print(find_element(x, lst))
输出结果是预期的。
(1, 1)
(-1, -1)
(1, 2)
在我们深入研究下一个解决方案之前,请随时在这里找到关于enumerate() 函数的深入解释。
The postHow to Find the Index of an Element in a List of Lists?first appeared onFinxter.