展平列表

PythonPythonBeginner
立即练习

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

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

简介

在 Python 中,列表(list)可以包含其他列表作为元素。这被称为嵌套列表(nested list)。有时,我们可能需要将嵌套列表展平为单个列表。在这个挑战中,你将被要求编写一个函数,将列表的列表展平一次。


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/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") subgraph Lab Skills python/comments -.-> lab-13641{{"展平列表"}} python/for_loops -.-> lab-13641{{"展平列表"}} python/list_comprehensions -.-> lab-13641{{"展平列表"}} python/lists -.-> lab-13641{{"展平列表"}} python/tuples -.-> lab-13641{{"展平列表"}} python/function_definition -.-> lab-13641{{"展平列表"}} end

展平列表

编写一个名为 flatten(lst) 的 Python 函数,该函数接受一个列表的列表作为参数,并返回一个展平后的列表。该函数应该只展平列表一次,这意味着原始列表中的任何嵌套列表都应该被展平,但这些嵌套列表中的任何嵌套列表都应该保持不变。

要解决这个问题,你可以使用列表推导式按顺序从子列表中提取每个值。

def flatten(lst):
  return [x for y in lst for x in y]
flatten([[1, 2, 3, 4], [5, 6, 7, 8]]) ## [1, 2, 3, 4, 5, 6, 7, 8]

总结

在这个挑战中,你学习了如何编写一个 Python 函数来一次性展平一个列表的列表。你使用了列表推导式按顺序从子列表中提取每个值。在处理 Python 中的嵌套列表时,这是一项很有用的技能。