n 个最小元素

PythonPythonBeginner
立即练习

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

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

简介

在这个挑战中,你需要编写一个 Python 函数,该函数从给定列表中返回 n 个最小的元素。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/default_arguments("Default Arguments") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/booleans -.-> lab-13695{{"n 个最小元素"}} python/comments -.-> lab-13695{{"n 个最小元素"}} python/lists -.-> lab-13695{{"n 个最小元素"}} python/tuples -.-> lab-13695{{"n 个最小元素"}} python/function_definition -.-> lab-13695{{"n 个最小元素"}} python/default_arguments -.-> lab-13695{{"n 个最小元素"}} python/build_in_functions -.-> lab-13695{{"n 个最小元素"}} end

n 个最小元素

编写一个名为 min_n(lst, n = 1) 的函数,它接受一个列表 lst 和一个可选整数 n(默认值为 1)。该函数应返回一个新列表,其中包含原始列表 lst 中的 n 个最小元素。如果未提供 n,则函数应返回一个包含 lst 中最小元素的列表。

如果 n 大于或等于 lst 的长度,则函数应返回按升序排序的原始列表。

你的函数应按以下步骤完成此操作:

  1. 使用内置的 sorted() 函数对列表进行升序排序。
  2. 使用切片表示法获取指定数量的元素。
  3. 返回结果列表。
def min_n(lst, n = 1):
  return sorted(lst, reverse = False)[:n]
min_n([1, 2, 3]) ## [1]
min_n([1, 2, 3], 2) ## [1, 2]

总结

在这个挑战中,你学习了如何编写一个 Python 函数,该函数从给定列表中返回 n 个最小的元素。你还学习了如何使用内置的 sorted() 函数和切片表示法来完成这项任务。