找到最后一个匹配的索引

Beginner

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

简介

在 Python 中,我们可以使用列表推导式和 enumerate() 来找到列表中满足给定条件的最后一个元素的索引。这个挑战将测试你使用这些工具解决问题的能力。

找到最后一个匹配的索引

编写一个函数 find_last_index(lst, fn),它接受一个列表 lst 和一个函数 fn 作为参数。该函数应返回 lst 中最后一个使 fn 返回 True 的元素的索引。如果没有元素满足该条件,函数应返回 -1

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

总结

在这个挑战中,你学习了如何使用列表推导式和 enumerate() 来找到列表中满足给定条件的最后一个元素的索引。这是你 Python 工具库中一项很有用的技术!