从列表中查找最大元素

PythonPythonBeginner
立即练习

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

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

简介

在 Python 中,有很多方法可以操作列表。一个常见的任务是从列表中找到 n 个最大的元素。在这个挑战中,你将被要求编写一个函数,该函数返回列表中 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-13688{{"从列表中查找最大元素"}} python/comments -.-> lab-13688{{"从列表中查找最大元素"}} python/lists -.-> lab-13688{{"从列表中查找最大元素"}} python/tuples -.-> lab-13688{{"从列表中查找最大元素"}} python/function_definition -.-> lab-13688{{"从列表中查找最大元素"}} python/default_arguments -.-> lab-13688{{"从列表中查找最大元素"}} python/build_in_functions -.-> lab-13688{{"从列表中查找最大元素"}} end

N 个最大元素

编写一个函数 max_n(lst, n = 1),它接受一个列表 lst 和一个可选整数 n 作为参数,并返回给定列表中 n 个最大元素组成的列表。如果未提供 n,则函数应返回一个包含列表中最大元素的列表。如果 n 大于或等于列表的长度,则函数应返回按降序排序的原始列表。

你的任务是实现 max_n() 函数。

def max_n(lst, n = 1):
  return sorted(lst, reverse = True)[:n]
max_n([1, 2, 3]) ## [3]
max_n([1, 2, 3], 2) ## [3, 2]

总结

在这个挑战中,你已经学会了如何在 Python 中从列表中找到 n 个最大的元素。你已经实现了一个函数,该函数接受一个列表和一个可选整数作为参数,并返回给定列表中 n 个最大元素组成的列表。