值的所有索引

PythonPythonBeginner
立即练习

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

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,列表是一组有序且可变的元素集合。有时,我们需要在列表中找到特定值的所有索引。在这个挑战中,你将创建一个函数,该函数返回列表中某个元素所有出现位置的索引列表。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/ControlFlowGroup -.-> python/list_comprehensions("List Comprehensions") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/comments -.-> lab-13658{{"值的所有索引"}} python/conditional_statements -.-> lab-13658{{"值的所有索引"}} python/for_loops -.-> lab-13658{{"值的所有索引"}} python/list_comprehensions -.-> lab-13658{{"值的所有索引"}} python/lists -.-> lab-13658{{"值的所有索引"}} python/tuples -.-> lab-13658{{"值的所有索引"}} python/function_definition -.-> lab-13658{{"值的所有索引"}} python/build_in_functions -.-> lab-13658{{"值的所有索引"}} end

值的所有索引

编写一个名为 index_of_all(lst, value) 的 Python 函数,该函数接受一个列表 lst 和一个值 value 作为参数,并返回 valuelst 中所有出现位置的索引列表。

要解决这个问题,你可以使用 enumerate() 和列表推导式来检查每个元素是否等于 value,并将 i 添加到结果中。

def index_of_all(lst, value):
  return [i for i, x in enumerate(lst) if x == value]
index_of_all([1, 2, 1, 4, 5, 1], 1) ## [0, 2, 5]
index_of_all([1, 2, 3, 4], 6) ## []

总结

在这个挑战中,你学习了如何使用 Python 在列表中找到特定值的所有索引。你使用了 enumerate() 和列表推导式来检查每个元素是否等于 value,并将 i 添加到结果中。继续练习以提高你的 Python 技能!