找到匹配的索引

Beginner

This tutorial is from open-source community. Access the source code

简介

在 Python 中,经常需要找到列表中满足特定条件的第一个元素的索引。这可以使用列表推导式、enumerate()next() 来实现。在这个挑战中,你将负责编写一个函数,该函数找到列表中满足给定测试函数的第一个元素的索引。

找到匹配的索引

编写一个函数 find_index(lst, fn),它接受一个列表 lst 和一个测试函数 fn 作为参数。该函数应返回 lst 中第一个使 fn 返回 True 的元素的索引。

def find_index(lst, fn):
  return next(i for i, x in enumerate(lst) if fn(x))
find_index([1, 2, 3, 4], lambda n: n % 2 == 1) ## 0

总结

在这个挑战中,你已经学会了如何找到列表中满足给定测试函数的第一个元素的索引。这可以通过使用列表推导式、enumerate()next() 来实现。