Identificación del objeto iterable más largo

PythonPythonBeginner
Practicar Ahora

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

💡 Este tutorial está traducido por IA desde la versión en inglés. Para ver la versión original, puedes hacer clic aquí

Introducción

En este desafío, escribirás una función que tome cualquier número de objetos iterables o objetos con una propiedad length y devuelva el más largo.


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/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/keyword_arguments("Keyword Arguments") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/comments -.-> lab-13683{{"Identificación del objeto iterable más largo"}} python/lists -.-> lab-13683{{"Identificación del objeto iterable más largo"}} python/tuples -.-> lab-13683{{"Identificación del objeto iterable más largo"}} python/function_definition -.-> lab-13683{{"Identificación del objeto iterable más largo"}} python/keyword_arguments -.-> lab-13683{{"Identificación del objeto iterable más largo"}} python/build_in_functions -.-> lab-13683{{"Identificación del objeto iterable más largo"}} end

Elemento más largo

Escribe una función longest_item(*args) que tome cualquier número de objetos iterables o objetos con una propiedad length y devuelva el más largo. La función debe:

  • Utilizar max() con len() como key para devolver el elemento con la mayor longitud.
  • Si varios elementos tienen la misma longitud, se devolverá el primero.
def longest_item(*args):
  return max(args, key = len)
longest_item('this', 'is', 'a', 'testcase') ## 'testcase'
longest_item([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]) ## [1, 2, 3, 4, 5]
longest_item([1, 2, 3], 'foobar') ## 'foobar'

Resumen

En este desafío, aprendiste cómo escribir una función que tome cualquier número de objetos iterables o objetos con una propiedad length y devuelva el más largo. Utilizaste max() con len() como key para devolver el elemento con la mayor longitud. Si varios elementos tienen la misma longitud, se devolverá el primero.