# Copyright (C) 2001-2020, Python Software Foundation # This file is distributed under the same license as the Python package. # Maintained by the python-doc-es workteam. # docs-es@python.org / # https://mail.python.org/mailman3/lists/docs-es.python.org/ # Check https://github.com/python/python-docs-es/blob/3.8/TRANSLATORS to # get the list of volunteers # msgid "" msgstr "" "Project-Id-Version: Python 3.8\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2022-10-25 19:47+0200\n" "PO-Revision-Date: 2021-10-22 10:38-0500\n" "Last-Translator: Kevin Cajachuán \n" "Language: es\n" "Language-Team: python-doc-es\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.10.3\n" #: ../Doc/howto/functional.rst:3 msgid "Functional Programming HOWTO" msgstr "HOWTO - Programación funcional" #: ../Doc/howto/functional.rst msgid "Author" msgstr "Autor" #: ../Doc/howto/functional.rst:5 msgid "A. M. Kuchling" msgstr "A. M. Kuchling" #: ../Doc/howto/functional.rst msgid "Release" msgstr "Publicación" #: ../Doc/howto/functional.rst:6 msgid "0.32" msgstr "0.32" #: ../Doc/howto/functional.rst:8 msgid "" "In this document, we'll take a tour of Python's features suitable for " "implementing programs in a functional style. After an introduction to the " "concepts of functional programming, we'll look at language features such as :" "term:`iterator`\\s and :term:`generator`\\s and relevant library modules " "such as :mod:`itertools` and :mod:`functools`." msgstr "" "En este documento, haremos un recorrido de las características de Python " "adecuadas para implementar programas en un estilo funcional. Después de una " "introducción de los conceptos de programación funcional, veremos las " "características del lenguaje como :term:`iterador `\\es y :term:" "`generador `\\es y módulos de librería relevantes como :mod:" "`itertools` y :mod:`functools`." #: ../Doc/howto/functional.rst:16 msgid "Introduction" msgstr "Introducción" #: ../Doc/howto/functional.rst:18 msgid "" "This section explains the basic concept of functional programming; if you're " "just interested in learning about Python language features, skip to the next " "section on :ref:`functional-howto-iterators`." msgstr "" "Esta sección explica el concepto básico de programación funcional; si solo " "está interesado en aprender acerca de las características del lenguaje " "Python, pase a la siguiente sección en :ref:`iteradores `." #: ../Doc/howto/functional.rst:22 msgid "" "Programming languages support decomposing problems in several different ways:" msgstr "" "Los lenguajes de programación soportan la descomposición de problemas en " "muchas formas diferentes:" #: ../Doc/howto/functional.rst:24 msgid "" "Most programming languages are **procedural**: programs are lists of " "instructions that tell the computer what to do with the program's input. C, " "Pascal, and even Unix shells are procedural languages." msgstr "" "La mayoría de los lenguajes de programación son **procedimentales**: los " "programas son listas de instrucciones que le dicen a la computadora qué " "hacer con la entrada del programa. C, Pascal e incluso las terminales Unix " "son lenguajes procedimentales." #: ../Doc/howto/functional.rst:28 msgid "" "In **declarative** languages, you write a specification that describes the " "problem to be solved, and the language implementation figures out how to " "perform the computation efficiently. SQL is the declarative language you're " "most likely to be familiar with; a SQL query describes the data set you want " "to retrieve, and the SQL engine decides whether to scan tables or use " "indexes, which subclauses should be performed first, etc." msgstr "" "En los lenguajes **declarativos**, se escribe una especificación que " "describe el problema que se resolverá, y la implementación del lenguaje " "averigua como realizar el cálculo de forma eficiente. SQL es el lenguaje " "declarativo con el que probablemente esté más familiarizado; una consulta " "SQL describe el conjunto de datos que quiere recuperar, y el motor SQL " "decide si escanear tablas o usar índices, qué subcláusulas deben ejecutarse " "primero, etc." #: ../Doc/howto/functional.rst:35 msgid "" "**Object-oriented** programs manipulate collections of objects. Objects " "have internal state and support methods that query or modify this internal " "state in some way. Smalltalk and Java are object-oriented languages. C++ " "and Python are languages that support object-oriented programming, but don't " "force the use of object-oriented features." msgstr "" "Los programas **orientados a objetos** manipulan colecciones de objetos. Los " "objetos tienen estado interno y soportan métodos que consultan o modifican " "su estado interno de alguna manera. Smalltalk y Java son lenguajes " "orientados a objetos. C++ y Python son lenguajes que soportan la " "programación orientada a objetos, pero no fuerzan el uso de las " "características orientadas a objetos." #: ../Doc/howto/functional.rst:41 msgid "" "**Functional** programming decomposes a problem into a set of functions. " "Ideally, functions only take inputs and produce outputs, and don't have any " "internal state that affects the output produced for a given input. Well-" "known functional languages include the ML family (Standard ML, OCaml, and " "other variants) and Haskell." msgstr "" "La programación **funcional** descompone un problema en un conjunto de " "funciones. Idealmente, las funciones solo reciben entradas y producen " "salidas, y no tienen ningún estado interno que afecte la salida producida " "para una entrada dada. Los lenguajes funcionales bien conocidos incluyen la " "familia ML (Standard ML, OCaml, y otras variantes) y Haskell." #: ../Doc/howto/functional.rst:47 msgid "" "The designers of some computer languages choose to emphasize one particular " "approach to programming. This often makes it difficult to write programs " "that use a different approach. Other languages are multi-paradigm languages " "that support several different approaches. Lisp, C++, and Python are multi-" "paradigm; you can write programs or libraries that are largely procedural, " "object-oriented, or functional in all of these languages. In a large " "program, different sections might be written using different approaches; the " "GUI might be object-oriented while the processing logic is procedural or " "functional, for example." msgstr "" "Los diseñadores de algunos lenguajes de computadora eligen enfatizar en un " "enfoque particular para programar. Esto a menudo hace difícil escribir " "programas que usen un enfoque diferente. Otros lenguajes son lenguajes " "multiparadigma que soportan varios enfoques diferentes. Lisp, C++ y Python " "son multiparadigma; puede escribir programas o librerías que son en gran " "parte procedimentales, orientados a objetos o funcionales en todos estos " "lenguajes. En un programa grande, las diferentes secciones podrían " "escribirse usando diferentes enfoques; la GUI podría ser orientada a objetos " "mientras la lógica de procesamiento es procedimental o funcional, por " "ejemplo." #: ../Doc/howto/functional.rst:58 msgid "" "In a functional program, input flows through a set of functions. Each " "function operates on its input and produces some output. Functional style " "discourages functions with side effects that modify internal state or make " "other changes that aren't visible in the function's return value. Functions " "that have no side effects at all are called **purely functional**. Avoiding " "side effects means not using data structures that get updated as a program " "runs; every function's output must only depend on its input." msgstr "" "En un programa funcional, la entrada fluye a través de un conjunto de " "funciones. Cada función opera sobre su entrada y produce alguna salida. El " "estilo funcional desalienta las funciones con efectos secundarios que " "modifican el estado interno o hacen otros cambios que no son visibles en el " "valor de retorno de la función. Las funciones que no tienen ningún efecto " "secundario se llaman **puramente funcionales**. Evitar los efectos " "secundarios significa no usar estructuras de datos que se actualicen " "mientras se ejecuta un programa; cada salida de la función debe depender " "solo de su entrada." #: ../Doc/howto/functional.rst:66 msgid "" "Some languages are very strict about purity and don't even have assignment " "statements such as ``a=3`` or ``c = a + b``, but it's difficult to avoid all " "side effects, such as printing to the screen or writing to a disk file. " "Another example is a call to the :func:`print` or :func:`time.sleep` " "function, neither of which returns a useful value. Both are called only for " "their side effects of sending some text to the screen or pausing execution " "for a second." msgstr "" "Algunos lenguajes son demasiado estrictos y ni siquiera tienen declaraciones " "de asignación como ``a=3`` o ``c = a + b``, pero es difícil evitar todos los " "efectos secundarios, como imprimir en pantalla o escribir en un archivo de " "disco. Otro ejemplo es llamar a las funciones :func:`print` o :func:`time." "sleep`, ninguna de las dos retorna un valor útil, ambas son llamadas solo " "por sus efectos secundarios de enviar texto a la pantalla o pausar la " "ejecución por un segundo." #: ../Doc/howto/functional.rst:73 msgid "" "Python programs written in functional style usually won't go to the extreme " "of avoiding all I/O or all assignments; instead, they'll provide a " "functional-appearing interface but will use non-functional features " "internally. For example, the implementation of a function will still use " "assignments to local variables, but won't modify global variables or have " "other side effects." msgstr "" "Los programas de Python escritos en estilo funcional usualmente no irán al " "extremo de evitar todas las E/S o todas las asignaciones; en cambio, " "proveerán una interfaz aparentemente funcional pero internamente usará " "características no funcionales. Por ejemplo, la implementación de una " "función todavía usará asignaciones a variables locales, pero no modificará " "variables globales ni tendrá otros efectos secundarios." #: ../Doc/howto/functional.rst:79 msgid "" "Functional programming can be considered the opposite of object-oriented " "programming. Objects are little capsules containing some internal state " "along with a collection of method calls that let you modify this state, and " "programs consist of making the right set of state changes. Functional " "programming wants to avoid state changes as much as possible and works with " "data flowing between functions. In Python you might combine the two " "approaches by writing functions that take and return instances representing " "objects in your application (e-mail messages, transactions, etc.)." msgstr "" "La programación funcional se puede considerar lo opuesto a la programación " "orientada a objetos. Los objetos son pequeñas capsulas que contienen algún " "estado interno junto con una colección de llamadas a métodos que le permiten " "modificar este estado, y los programas consisten en realizar el conjunto " "correcto de cambios de estado. La programación funcional quiere evitar " "cambios de estado tanto como sea posible y trabaja con flujos de datos entre " "funciones. En Python podría combinar los dos enfoques para escribir " "funciones que reciban y retornen instancias que representen objetos en su " "aplicación (mensajes de e-mail, transacciones, etc.)." #: ../Doc/howto/functional.rst:88 msgid "" "Functional design may seem like an odd constraint to work under. Why should " "you avoid objects and side effects? There are theoretical and practical " "advantages to the functional style:" msgstr "" "El diseño funcional puede parecer una restricción extraña bajo la cuál " "trabajar. ¿Por qué evitaría objetos y efectos secundarios? Hay ventajas " "teóricas y prácticas para el estilo funcional:" #: ../Doc/howto/functional.rst:92 msgid "Formal provability." msgstr "Demostrabilidad formal." #: ../Doc/howto/functional.rst:93 msgid "Modularity." msgstr "Modularidad." #: ../Doc/howto/functional.rst:94 msgid "Composability." msgstr "Componibilidad." #: ../Doc/howto/functional.rst:95 msgid "Ease of debugging and testing." msgstr "Facilidad de depurar y probar." #: ../Doc/howto/functional.rst:99 msgid "Formal provability" msgstr "Demostrabilidad formal" #: ../Doc/howto/functional.rst:101 msgid "" "A theoretical benefit is that it's easier to construct a mathematical proof " "that a functional program is correct." msgstr "" "Un beneficio teórico es que es más fácil construir una demostración " "matemática de que un programa funcional es correcto." #: ../Doc/howto/functional.rst:104 msgid "" "For a long time researchers have been interested in finding ways to " "mathematically prove programs correct. This is different from testing a " "program on numerous inputs and concluding that its output is usually " "correct, or reading a program's source code and concluding that the code " "looks right; the goal is instead a rigorous proof that a program produces " "the right result for all possible inputs." msgstr "" "Por un largo tiempo los investigadores se han interesado en buscar formas de " "demostrar matemáticamente que los programas son correctos. Esto es diferente " "de probar un programa sobre numerosas entradas y concluir que su salida es " "usualmente correcta, o leer el código fuente de un programa y concluir que " "el código se ve bien; en lugar de eso el objetivo es una demostración " "rigurosa de que un programa produce el resultado correcto para todas las " "entradas posibles." #: ../Doc/howto/functional.rst:111 msgid "" "The technique used to prove programs correct is to write down " "**invariants**, properties of the input data and of the program's variables " "that are always true. For each line of code, you then show that if " "invariants X and Y are true **before** the line is executed, the slightly " "different invariants X' and Y' are true **after** the line is executed. " "This continues until you reach the end of the program, at which point the " "invariants should match the desired conditions on the program's output." msgstr "" "La técnica utilizada para demostrar que los programas son correctos es " "anotar **invariantes**, propiedades de los datos de entrada y de las " "variables del programa que siempre son verdaderas. Por cada línea de código, " "debe mostrar que si las invariantes X e Y son verdaderas **antes** que la " "línea sea ejecutada, las invariantes ligeramente diferentes X' e Y' son " "verdaderas **después** que la línea se ejecutó. Esto continúa hasta que " "alcance el fin del programa, punto en el cuál las invariantes deben " "coincidir con las condiciones deseadas en la salida del programa." #: ../Doc/howto/functional.rst:119 msgid "" "Functional programming's avoidance of assignments arose because assignments " "are difficult to handle with this technique; assignments can break " "invariants that were true before the assignment without producing any new " "invariants that can be propagated onward." msgstr "" "La evitación de las asignaciones de la programación funcional surge porque " "las asignaciones son difíciles de manejar con esta técnica; las asignaciones " "pueden romper invariantes que eran verdaderas antes de la asignación sin " "producir nuevas invariantes que se puedan propagar hacia adelante." #: ../Doc/howto/functional.rst:124 msgid "" "Unfortunately, proving programs correct is largely impractical and not " "relevant to Python software. Even trivial programs require proofs that are " "several pages long; the proof of correctness for a moderately complicated " "program would be enormous, and few or none of the programs you use daily " "(the Python interpreter, your XML parser, your web browser) could be proven " "correct. Even if you wrote down or generated a proof, there would then be " "the question of verifying the proof; maybe there's an error in it, and you " "wrongly believe you've proved the program correct." msgstr "" "Desafortunadamente, demostrar que los programas son correctos es en gran " "parte impráctico y no relevante al software de Python. Incluso los programas " "triviales requieren demostraciones que tienen varias páginas; la " "demostración de correctitud para un programa moderadamente complicado sería " "enorme, y pocos o ninguno de los programas que usa diariamente (el " "interprete de Python, su analizador XML, su navegador web) se podrían " "demostrar que son correctos. Aún si anotó o generó una demostración, " "entonces estaría la cuestión de verificar la demostración; quizás hay un " "error en ella, y equivocadamente cree que demostró que el programa es " "correcto." #: ../Doc/howto/functional.rst:135 msgid "Modularity" msgstr "Modularidad" #: ../Doc/howto/functional.rst:137 msgid "" "A more practical benefit of functional programming is that it forces you to " "break apart your problem into small pieces. Programs are more modular as a " "result. It's easier to specify and write a small function that does one " "thing than a large function that performs a complicated transformation. " "Small functions are also easier to read and to check for errors." msgstr "" "Un beneficio más práctico de la programación funcional es que fuerza a " "romper su problema en pequeñas piezas. Como resultado los programas son más " "modulares. Es más fácil especificar y escribir una función pequeña que hace " "una cosa que una función grande que realiza una transformación complicada. " "Las funciones pequeñas también son más fáciles de leer y comprobar si hay " "errores." #: ../Doc/howto/functional.rst:145 msgid "Ease of debugging and testing" msgstr "Facilidad de depurar y probar" #: ../Doc/howto/functional.rst:147 msgid "Testing and debugging a functional-style program is easier." msgstr "Probar y depurar un programa en estilo funcional es más fácil." #: ../Doc/howto/functional.rst:149 msgid "" "Debugging is simplified because functions are generally small and clearly " "specified. When a program doesn't work, each function is an interface point " "where you can check that the data are correct. You can look at the " "intermediate inputs and outputs to quickly isolate the function that's " "responsible for a bug." msgstr "" "La depuración se simplifica porque las funciones generalmente son pequeñas y " "claramente especificadas. Cuando un programa no funciona, cada función es un " "punto de interfaz donde puede comprobar si los datos son correctos. Puede " "ver las entradas y salidas intermedias para aislar rápidamente la función " "que es responsable de un error." #: ../Doc/howto/functional.rst:154 msgid "" "Testing is easier because each function is a potential subject for a unit " "test. Functions don't depend on system state that needs to be replicated " "before running a test; instead you only have to synthesize the right input " "and then check that the output matches expectations." msgstr "" "Las pruebas son más fáciles porque cada función es un sujeto potencial para " "una prueba unitaria. Las funciones no dependen de un estado del sistema que " "necesite ser replicado antes de correr una prueba; en lugar de eso solo " "tiene que sintetizar la entrada correcta y comprobar que la salida coincida " "con las expectativas." #: ../Doc/howto/functional.rst:161 msgid "Composability" msgstr "Componibilidad" #: ../Doc/howto/functional.rst:163 msgid "" "As you work on a functional-style program, you'll write a number of " "functions with varying inputs and outputs. Some of these functions will be " "unavoidably specialized to a particular application, but others will be " "useful in a wide variety of programs. For example, a function that takes a " "directory path and returns all the XML files in the directory, or a function " "that takes a filename and returns its contents, can be applied to many " "different situations." msgstr "" "Mientras trabaja en un programa en estilo funcional, escribirá un número de " "funciones con diferentes entradas y salidas. Algunas de estas funciones " "inevitablemente estarán especializadas en una aplicación en particular, pero " "otras serán útiles en una amplia variedad de programas. Por ejemplo, una " "función que recibe la ruta de un directorio y retorna todos los archivos XML " "en el directorio, o una función que recibe el nombre de un archivo y retorna " "su contenido, se puede aplicar a muchas situaciones diferentes." #: ../Doc/howto/functional.rst:170 msgid "" "Over time you'll form a personal library of utilities. Often you'll " "assemble new programs by arranging existing functions in a new configuration " "and writing a few functions specialized for the current task." msgstr "" "Con el tiempo formará una librería personal de utilidades. A menudo " "ensamblará nuevos programas organizando funciones existentes en una nueva " "configuración y escribiendo unas pocas funciones especializadas para la " "tarea actual." #: ../Doc/howto/functional.rst:178 msgid "Iterators" msgstr "Iteradores" #: ../Doc/howto/functional.rst:180 msgid "" "I'll start by looking at a Python language feature that's an important " "foundation for writing functional-style programs: iterators." msgstr "" "Comenzaré viendo una característica del lenguaje Python que es una base " "importante para escribir programas en estilo funcional: iteradores." #: ../Doc/howto/functional.rst:183 msgid "" "An iterator is an object representing a stream of data; this object returns " "the data one element at a time. A Python iterator must support a method " "called :meth:`~iterator.__next__` that takes no arguments and always returns " "the next element of the stream. If there are no more elements in the " "stream, :meth:`~iterator.__next__` must raise the :exc:`StopIteration` " "exception. Iterators don't have to be finite, though; it's perfectly " "reasonable to write an iterator that produces an infinite stream of data." msgstr "" "Un iterador es un objeto que representa un flujo de datos; este objeto " "retorna los datos de a un elemento a la vez. Un iterador de Python debe " "soportar un método llamado :meth:`~iterator.__next__` que no recibe " "argumentos y siempre retorna el siguiente elemento en el flujo. Si no hay " "más elementos en el flujo, :meth:`~iterator.__next__` debe lanzar la " "excepción :exc:`StopIteration`. Los iteradores no tienen que ser finitos; es " "perfectamente razonable escribir un iterador que produce un flujo de datos " "infinito." #: ../Doc/howto/functional.rst:191 msgid "" "The built-in :func:`iter` function takes an arbitrary object and tries to " "return an iterator that will return the object's contents or elements, " "raising :exc:`TypeError` if the object doesn't support iteration. Several " "of Python's built-in data types support iteration, the most common being " "lists and dictionaries. An object is called :term:`iterable` if you can get " "an iterator for it." msgstr "" "La función incorporada :func:`iter` recibe un objeto arbitrario e intenta " "retornar un iterador que retornará los contenidos o elementos del objeto, " "lanzando :exc:`TypeError` si el objeto no soporta iteración. Muchos tipos de " "datos integrados de Python soportan iteración, siendo los más comunes las " "listas y los diccionarios. Un objeto se llama :term:`iterable` si puede " "obtener un iterador para él." #: ../Doc/howto/functional.rst:198 msgid "You can experiment with the iteration interface manually:" msgstr "Puede experimentar con la interfaz de iteración manualmente:" #: ../Doc/howto/functional.rst:216 msgid "" "Python expects iterable objects in several different contexts, the most " "important being the :keyword:`for` statement. In the statement ``for X in " "Y``, Y must be an iterator or some object for which :func:`iter` can create " "an iterator. These two statements are equivalent::" msgstr "" "Python espera objetos iterables en muchos contextos diferentes, siendo el " "más importante la sentencia :keyword:`for`. En la sentencia ``for X in Y``, " "Y debe ser un iterador o algún objeto para el que :func:`iter` puede crear " "un iterador. Estas dos sentencias son equivalentes::" #: ../Doc/howto/functional.rst:228 msgid "" "Iterators can be materialized as lists or tuples by using the :func:`list` " "or :func:`tuple` constructor functions:" msgstr "" "Los iteradores se pueden materializar como listas o tuplas utilizando las " "funciones constructoras :func:`list` o :func:`tuple`:" #: ../Doc/howto/functional.rst:237 msgid "" "Sequence unpacking also supports iterators: if you know an iterator will " "return N elements, you can unpack them into an N-tuple:" msgstr "" "El desempaquetado de secuencias también soporta iteradores: si sabe que un " "iterador retornará N elementos, puede desempaquetarlos en una N-tupla:" #: ../Doc/howto/functional.rst:246 msgid "" "Built-in functions such as :func:`max` and :func:`min` can take a single " "iterator argument and will return the largest or smallest element. The " "``\"in\"`` and ``\"not in\"`` operators also support iterators: ``X in " "iterator`` is true if X is found in the stream returned by the iterator. " "You'll run into obvious problems if the iterator is infinite; :func:`max`, :" "func:`min` will never return, and if the element X never appears in the " "stream, the ``\"in\"`` and ``\"not in\"`` operators won't return either." msgstr "" "Las funciones incorporadas como :func:`max` y :func:`min` pueden recibir un " "solo iterador como argumento y retornarán el elemento más grande o más " "pequeño. Los operadores ``\"in\"`` y ``\"not in\"`` también soportan " "iteradores: ``X in iterator`` es verdadero si X se encuentra en el flujo que " "retornó el iterador. Se encontrará con problemas obvios si el iterador es " "infinito; :func:`max`, :func:`min` nunca retornarán, y si el elemento X " "nunca aparece en el flujo, los operadores ``\"in\"`` y ``\"not in\"`` " "tampoco retornarán." #: ../Doc/howto/functional.rst:254 msgid "" "Note that you can only go forward in an iterator; there's no way to get the " "previous element, reset the iterator, or make a copy of it. Iterator " "objects can optionally provide these additional capabilities, but the " "iterator protocol only specifies the :meth:`~iterator.__next__` method. " "Functions may therefore consume all of the iterator's output, and if you " "need to do something different with the same stream, you'll have to create a " "new iterator." msgstr "" "Note que solo puede ir hacia adelante en un iterador; no hay forma de " "obtener el elemento anterior, reiniciar el iterador o hacer una copia de él. " "Los objetos iteradores opcionalmente pueden proveer estas capacidades " "adicionales, pero el protocolo del iterador solo especifica el método :meth:" "`~iterator.__next__`. Por lo tanto las funciones pueden consumir toda la " "salida del iterador, y si necesita hacer algo diferente con el mismo flujo, " "tendrá que crear un nuevo iterador." #: ../Doc/howto/functional.rst:264 msgid "Data Types That Support Iterators" msgstr "Tipos de datos que soportan iteradores" #: ../Doc/howto/functional.rst:266 msgid "" "We've already seen how lists and tuples support iterators. In fact, any " "Python sequence type, such as strings, will automatically support creation " "of an iterator." msgstr "" "Ya hemos visto cómo las listas y tuplas soportan iteradores. De hecho, " "cualquier tipo de secuencia de Python, como cadenas de caracteres, " "automáticamente soportará la creación de un iterador." #: ../Doc/howto/functional.rst:270 msgid "" "Calling :func:`iter` on a dictionary returns an iterator that will loop over " "the dictionary's keys::" msgstr "" "Llamar a :func:`iter` en un diccionario retornará un iterador que recorrerá " "sobre las claves del diccionario::" #: ../Doc/howto/functional.rst:290 msgid "" "Note that starting with Python 3.7, dictionary iteration order is guaranteed " "to be the same as the insertion order. In earlier versions, the behaviour " "was unspecified and could vary between implementations." msgstr "" "Note que a partir de Python 3.7, se garantiza que el orden de iteración del " "diccionario es el mismo que el orden de inserción. En versiones anteriores, " "el comportamiento no estaba especificado y podía variar entre " "implementaciones." #: ../Doc/howto/functional.rst:294 msgid "" "Applying :func:`iter` to a dictionary always loops over the keys, but " "dictionaries have methods that return other iterators. If you want to " "iterate over values or key/value pairs, you can explicitly call the :meth:" "`~dict.values` or :meth:`~dict.items` methods to get an appropriate iterator." msgstr "" "Aplicar :func:`iter` a un diccionario siempre recorre sobre las claves, pero " "los diccionarios tienen métodos que retornan otros iteradores. Si quiere " "iterar sobre valores o pares clave/valor, puede explícitamente llamar a los " "métodos :meth:`~dict.values` o :meth:`~dict.items` para obtener un iterador " "apropiado." #: ../Doc/howto/functional.rst:300 msgid "" "The :func:`dict` constructor can accept an iterator that returns a finite " "stream of ``(key, value)`` tuples:" msgstr "" "El constructor :func:`dict` puede aceptar un iterador que retorna un flujo " "finito de tuplas ``(key, value)``:" #: ../Doc/howto/functional.rst:307 msgid "" "Files also support iteration by calling the :meth:`~io.TextIOBase.readline` " "method until there are no more lines in the file. This means you can read " "each line of a file like this::" msgstr "" "Los archivos también soportan iteración llamando al método :meth:`~io." "TextIOBase.readline` hasta que no haya más líneas en el archivo. Esto " "significa que puede leer cada línea de un archivo de esta forma::" #: ../Doc/howto/functional.rst:315 msgid "" "Sets can take their contents from an iterable and let you iterate over the " "set's elements::" msgstr "" "Los conjuntos pueden recibir sus contenidos de un iterable y le permiten " "iterar sobre los elementos del conjunto::" #: ../Doc/howto/functional.rst:331 msgid "Generator expressions and list comprehensions" msgstr "Expresiones generadoras y listas por comprensión" #: ../Doc/howto/functional.rst:333 msgid "" "Two common operations on an iterator's output are 1) performing some " "operation for every element, 2) selecting a subset of elements that meet " "some condition. For example, given a list of strings, you might want to " "strip off trailing whitespace from each line or extract all the strings " "containing a given substring." msgstr "" "Dos operaciones comunes en la salida de un iterador son 1) realizar alguna " "operación para cada elemento, 2) elegir un subconjunto de elementos que " "reúnen alguna condición. Por ejemplo, dada una lista de cadena de " "caracteres, podría querer remover los espacios finales de cada línea o " "extraer todas las cadenas de caracteres que contienen una subcadena de " "caracteres dada." #: ../Doc/howto/functional.rst:339 msgid "" "List comprehensions and generator expressions (short form: \"listcomps\" and " "\"genexps\") are a concise notation for such operations, borrowed from the " "functional programming language Haskell (https://www.haskell.org/). You can " "strip all the whitespace from a stream of strings with the following code::" msgstr "" "Las listas por comprensión y las expresiones generadoras (forma abreviada: " "\"listcomps\" y \"genexps\") son una notación concisa para tales " "operaciones, prestadas del lenguaje de programación funcional Haskell " "(https://www.haskell.org/). Puede remover todos los espacios de un flujo de " "cadena de caracteres con el siguiente código::" #: ../Doc/howto/functional.rst:352 msgid "" "You can select only certain elements by adding an ``\"if\"`` condition::" msgstr "" "Puede seleccionar solo ciertos elementos agregando una condición ``\"if\"``::" #: ../Doc/howto/functional.rst:357 msgid "" "With a list comprehension, you get back a Python list; ``stripped_list`` is " "a list containing the resulting lines, not an iterator. Generator " "expressions return an iterator that computes the values as necessary, not " "needing to materialize all the values at once. This means that list " "comprehensions aren't useful if you're working with iterators that return an " "infinite stream or a very large amount of data. Generator expressions are " "preferable in these situations." msgstr "" "Con una lista por comprensión, obtiene una lista de Python; " "``stripped_list`` es una lista que contiene las líneas resultantes, no un " "iterador. Las expresiones generadoras retornan un iterador que calcula los " "valores cuando es necesario, sin necesidad de materializar todos los valores " "a la vez. Esto significa que las listas por comprensión son inútiles si está " "trabajando con iteradores que retornan un flujo infinito o una gran cantidad " "de datos. En estas situaciones son preferibles las expresiones generadoras." #: ../Doc/howto/functional.rst:364 msgid "" "Generator expressions are surrounded by parentheses (\"()\") and list " "comprehensions are surrounded by square brackets (\"[]\"). Generator " "expressions have the form::" msgstr "" "Las expresiones generadoras están rodeadas por paréntesis (\"()\") y las " "listas por comprensión están rodeadas por corchetes (\"[]\"). Las " "expresiones generadoras tienen la forma::" #: ../Doc/howto/functional.rst:378 msgid "" "Again, for a list comprehension only the outside brackets are different " "(square brackets instead of parentheses)." msgstr "" "Nuevamente, para una lista por comprensión solo los corchetes exteriores son " "diferentes (corchetes en lugar de paréntesis)." #: ../Doc/howto/functional.rst:381 msgid "" "The elements of the generated output will be the successive values of " "``expression``. The ``if`` clauses are all optional; if present, " "``expression`` is only evaluated and added to the result when ``condition`` " "is true." msgstr "" "Los elementos de la salida generada serán valores sucesivos de " "``expression``. Las cláusulas ``if`` son todas opcionales; si está presente, " "``expression`` es solo evaluado y añadido al resultado cuando ``condition`` " "es verdadero." #: ../Doc/howto/functional.rst:385 msgid "" "Generator expressions always have to be written inside parentheses, but the " "parentheses signalling a function call also count. If you want to create an " "iterator that will be immediately passed to a function you can write::" msgstr "" "Las expresiones generadoras siempre se tienen que escribir dentro de " "paréntesis, pero los paréntesis que indican la llamada a una función también " "cuentan. Si quiere crear un iterador que se pase inmediatamente a una " "función puede escribir::" #: ../Doc/howto/functional.rst:391 msgid "" "The ``for...in`` clauses contain the sequences to be iterated over. The " "sequences do not have to be the same length, because they are iterated over " "from left to right, **not** in parallel. For each element in ``sequence1``, " "``sequence2`` is looped over from the beginning. ``sequence3`` is then " "looped over for each resulting pair of elements from ``sequence1`` and " "``sequence2``." msgstr "" "Las cláusulas ``for...in`` contienen las secuencias sobre las que se itera. " "Las secuencias no tienen que tener la misma longitud, porque son iteradas de " "izquierda a derecha, **no** en paralelo. Por cada elemento en ``sequence1``, " "se recorre ``sequence2`` desde el inicio. Luego se recorre ``sequence3`` por " "cada par de elementos resultante de ``sequence1`` y ``sequence2``." #: ../Doc/howto/functional.rst:397 msgid "" "To put it another way, a list comprehension or generator expression is " "equivalent to the following Python code::" msgstr "" "Para ponerlo en otra forma, una lista por comprensión o expresión generadora " "es equivalente al siguiente código Python::" #: ../Doc/howto/functional.rst:414 msgid "" "This means that when there are multiple ``for...in`` clauses but no ``if`` " "clauses, the length of the resulting output will be equal to the product of " "the lengths of all the sequences. If you have two lists of length 3, the " "output list is 9 elements long:" msgstr "" "Esto significa que cuando hay múltiples cláusulas ``for...in`` pero no " "cláusulas ``if``, la longitud de la salida resultante será igual al producto " "de las longitudes de todas las secuencias. Si tiene dos listas de longitud " "3, la lista de salida tendrá 9 elementos:" #: ../Doc/howto/functional.rst:426 msgid "" "To avoid introducing an ambiguity into Python's grammar, if ``expression`` " "is creating a tuple, it must be surrounded with parentheses. The first list " "comprehension below is a syntax error, while the second one is correct::" msgstr "" "Para evitar introducir una ambigüedad en la gramática de Python, si " "``expression`` está creando una tupla, debe estar rodeada de paréntesis. La " "primera lista por comprensión de abajo tiene un error de sintaxis, mientras " "que la segunda es correcta::" #: ../Doc/howto/functional.rst:437 msgid "Generators" msgstr "Generadores" #: ../Doc/howto/functional.rst:439 msgid "" "Generators are a special class of functions that simplify the task of " "writing iterators. Regular functions compute a value and return it, but " "generators return an iterator that returns a stream of values." msgstr "" "Los generadores son una clase especial de funciones que simplifican la tarea " "de escribir iteradores. Las funciones regulares calculan un valor y lo " "retornan, pero los generadores retornan un iterador que retorna un flujo de " "valores." #: ../Doc/howto/functional.rst:443 msgid "" "You're doubtless familiar with how regular function calls work in Python or " "C. When you call a function, it gets a private namespace where its local " "variables are created. When the function reaches a ``return`` statement, " "the local variables are destroyed and the value is returned to the caller. " "A later call to the same function creates a new private namespace and a " "fresh set of local variables. But, what if the local variables weren't " "thrown away on exiting a function? What if you could later resume the " "function where it left off? This is what generators provide; they can be " "thought of as resumable functions." msgstr "" "Sin duda está relacionado con cómo funcionan las llamadas a funciones " "regulares en Python o C. Cuando llama a una función, esta obtiene su espacio " "de nombres privado donde se crean sus variables locales. Cuando la función " "alcanza una sentencia ``return``, las variables locales son destruidas y el " "valor se retorna al llamador. Una llamada posterior a la misma función crea " "un nuevo espacio de nombres privado y un conjunto limpio de variables " "locales. Pero, ¿qué pasa si las variables locales no fueron desechadas en la " "salida de una función? ¿Qué pasa si más tarde podría reanudar la función " "desde donde quedó? Esto es lo que proveen los generadores; se pueden pensar " "como funciones que se reanudan." #: ../Doc/howto/functional.rst:452 msgid "Here's the simplest example of a generator function:" msgstr "Este es el ejemplo más simple de una función generadora:" #: ../Doc/howto/functional.rst:458 msgid "" "Any function containing a :keyword:`yield` keyword is a generator function; " "this is detected by Python's :term:`bytecode` compiler which compiles the " "function specially as a result." msgstr "" "Cualquier función que contiene una palabra clave :keyword:`yield` es una " "función generadora; esto es detectado por el compilador :term:`bytecode` de " "Python que compila la función de forma especial como resultado." #: ../Doc/howto/functional.rst:462 msgid "" "When you call a generator function, it doesn't return a single value; " "instead it returns a generator object that supports the iterator protocol. " "On executing the ``yield`` expression, the generator outputs the value of " "``i``, similar to a ``return`` statement. The big difference between " "``yield`` and a ``return`` statement is that on reaching a ``yield`` the " "generator's state of execution is suspended and local variables are " "preserved. On the next call to the generator's :meth:`~generator.__next__` " "method, the function will resume executing." msgstr "" "Cuando llama a una función generadora, no retorna un solo valor; en lugar de " "eso retorna un objeto generador que soporta el protocolo iterador. Al " "ejecutar la expresión ``yield``, el generador produce el valor de ``i``, de " "forma similar a una sentencia ``return``. La gran diferencia entre una " "sentencia ``yield`` y un ``return`` es que al alcanzar un ``yield`` se " "suspende el estado de ejecución del generador y se preservan las variables " "locales. En la próxima llamada al método :meth:`~generator.__next__` del " "generador, la función reanudará la ejecución." #: ../Doc/howto/functional.rst:471 msgid "Here's a sample usage of the ``generate_ints()`` generator:" msgstr "Este es un ejemplo de uso del generador ``generate_ints()``:" #: ../Doc/howto/functional.rst:488 msgid "" "You could equally write ``for i in generate_ints(5)``, or ``a, b, c = " "generate_ints(3)``." msgstr "" "De igual forma podría escribir ``for i in generate_ints(5)``, o ``a, b, c = " "generate_ints(3)``." #: ../Doc/howto/functional.rst:491 msgid "" "Inside a generator function, ``return value`` causes " "``StopIteration(value)`` to be raised from the :meth:`~generator.__next__` " "method. Once this happens, or the bottom of the function is reached, the " "procession of values ends and the generator cannot yield any further values." msgstr "" "Dentro de una función generadora, ``return value`` causa que se lance " "``StopIteration(value)`` del método :meth:`~generator.__next__`\\. Una vez " "que esto pase, o que se alcance el final de la función, termina la procesión " "de valores y el generador no puede producir más valores." #: ../Doc/howto/functional.rst:496 msgid "" "You could achieve the effect of generators manually by writing your own " "class and storing all the local variables of the generator as instance " "variables. For example, returning a list of integers could be done by " "setting ``self.count`` to 0, and having the :meth:`~iterator.__next__` " "method increment ``self.count`` and return it. However, for a moderately " "complicated generator, writing a corresponding class can be much messier." msgstr "" "Podría lograr el efecto de los generadores manualmente escribiendo su propia " "clase y guardando todas las variables locales del generador como variables " "de instancia. Por ejemplo, retornar una lista de enteros se podría hacer " "estableciendo ``self.count`` a 0, y teniendo el método :meth:`~iterator." "__next__` que incrementa ``self.count`` y lo retorna. Sin embargo, para un " "generador moderadamente complicado, escribir una clase correspondiente puede " "ser mucho más confuso." #: ../Doc/howto/functional.rst:504 msgid "" "The test suite included with Python's library, :source:`Lib/test/" "test_generators.py`, contains a number of more interesting examples. Here's " "one generator that implements an in-order traversal of a tree using " "generators recursively. ::" msgstr "" "El banco de pruebas incluido con la librería de Python, :source:`Lib/test/" "test_generators.py`, contiene un número de ejemplos más interesantes. Este " "es un generador que implementa un recorrido inorden de un árbol usando " "generadores recursivamente. ::" #: ../Doc/howto/functional.rst:520 msgid "" "Two other examples in ``test_generators.py`` produce solutions for the N-" "Queens problem (placing N queens on an NxN chess board so that no queen " "threatens another) and the Knight's Tour (finding a route that takes a " "knight to every square of an NxN chessboard without visiting any square " "twice)." msgstr "" "Otros dos ejemplos en ``test_generators.py`` producen soluciones al problema " "de N-reinas (ubicar N reinas en un tablero de ajedrez de NxN de forma que " "ninguna reina amenace a otra) y el problema del caballo (encontrar una ruta " "que lleve a un caballo a cada cuadro de un tablero de ajedrez de NxN sin " "visitar ningún cuadro dos veces)." #: ../Doc/howto/functional.rst:528 msgid "Passing values into a generator" msgstr "Pasar valores a un generador" #: ../Doc/howto/functional.rst:530 msgid "" "In Python 2.4 and earlier, generators only produced output. Once a " "generator's code was invoked to create an iterator, there was no way to pass " "any new information into the function when its execution is resumed. You " "could hack together this ability by making the generator look at a global " "variable or by passing in some mutable object that callers then modify, but " "these approaches are messy." msgstr "" "En Python 2.4 y anteriores, los generadores solo producían salida. Una vez " "que el código de un generador era invocado para crear un iterador, no había " "forma de pasar ninguna información nueva a la función cuando se reanuda su " "ejecución. Podría lograr esta habilidad haciendo que el generador mire una " "variable global o pasando en algún objeto mutable que el llamador luego " "modifica, pero estos enfoques son confusos." #: ../Doc/howto/functional.rst:537 msgid "" "In Python 2.5 there's a simple way to pass values into a generator. :keyword:" "`yield` became an expression, returning a value that can be assigned to a " "variable or otherwise operated on::" msgstr "" "En Python 2.5 hay una forma más simple de pasar valores a un generador. :" "keyword:`yield` se convirtió en una expresión, retornando un valor que se " "puede asignar a una variable o sobre el que se puede operar::" #: ../Doc/howto/functional.rst:543 msgid "" "I recommend that you **always** put parentheses around a ``yield`` " "expression when you're doing something with the returned value, as in the " "above example. The parentheses aren't always necessary, but it's easier to " "always add them instead of having to remember when they're needed." msgstr "" "Recomiendo que **siempre** ponga paréntesis alrededor de una expresión " "``yield`` cuando esté haciendo algo con el valor retornado, como en el " "ejemplo de arriba. Los paréntesis no siempre son necesarios, pero siempre es " "más fácil agregarlos en lugar de tener que recordar cuándo son necesarios." #: ../Doc/howto/functional.rst:548 msgid "" "(:pep:`342` explains the exact rules, which are that a ``yield``-expression " "must always be parenthesized except when it occurs at the top-level " "expression on the right-hand side of an assignment. This means you can " "write ``val = yield i`` but have to use parentheses when there's an " "operation, as in ``val = (yield i) + 12``.)" msgstr "" "(:pep:`342` explica las reglas exactas, que son que una expresión ``yield`` " "siempre debe estar entre paréntesis excepto cuando se encuentra en la " "expresión de primer nivel en el lado derecho de una asignación. Esto " "significa que puede escribir ``val = yield i`` pero tiene que usar " "paréntesis cuando hay una operación, como en ``val = (yield i) + 12``.)" #: ../Doc/howto/functional.rst:554 msgid "" "Values are sent into a generator by calling its :meth:`send(value) " "` method. This method resumes the generator's code and the " "``yield`` expression returns the specified value. If the regular :meth:" "`~generator.__next__` method is called, the ``yield`` returns ``None``." msgstr "" "Los valores son enviados a un generador llamando a su método :meth:" "`send(value) `. Este método reanuda el código del generador " "y la expresión ``yield`` retorna el valor especificado. Si se llama al " "método regular :meth:`~generator.__next__`, ``yield`` retorna ``None``." #: ../Doc/howto/functional.rst:559 msgid "" "Here's a simple counter that increments by 1 and allows changing the value " "of the internal counter." msgstr "" "Este es un simple contador que incrementa por 1 y permite cambiar los " "valores del contador interno." #: ../Doc/howto/functional.rst:574 msgid "And here's an example of changing the counter:" msgstr "Y este es un ejemplo del cambio del contador:" #: ../Doc/howto/functional.rst:591 msgid "" "Because ``yield`` will often be returning ``None``, you should always check " "for this case. Don't just use its value in expressions unless you're sure " "that the :meth:`~generator.send` method will be the only method used to " "resume your generator function." msgstr "" "Como ``yield`` a menudo retornará ``None``, siempre debería comprobar este " "caso. No use simplemente su valor en expresiones a menos que esté seguro que " "el método :meth:`~generator.send` será el único método utilizado para " "reanudar su función generadora." #: ../Doc/howto/functional.rst:596 msgid "" "In addition to :meth:`~generator.send`, there are two other methods on " "generators:" msgstr "" "Además del método :meth:`~generator.send`, hay otros dos métodos para " "generadores:" #: ../Doc/howto/functional.rst:599 #, fuzzy msgid "" ":meth:`throw(value) ` is used to raise an exception inside " "the generator; the exception is raised by the ``yield`` expression where the " "generator's execution is paused." msgstr "" ":meth:`throw(type, value=None, traceback=None) ` se usa " "para lanzar una excepción dentro del generador; la excepción se lanza en la " "expresión ``yield`` donde se pausa la ejecución del generador." #: ../Doc/howto/functional.rst:603 msgid "" ":meth:`~generator.close` raises a :exc:`GeneratorExit` exception inside the " "generator to terminate the iteration. On receiving this exception, the " "generator's code must either raise :exc:`GeneratorExit` or :exc:" "`StopIteration`; catching the exception and doing anything else is illegal " "and will trigger a :exc:`RuntimeError`. :meth:`~generator.close` will also " "be called by Python's garbage collector when the generator is garbage-" "collected." msgstr "" ":meth:`~generator.close` lanza una excepción :exc:`GeneratorExit` dentro del " "generador para terminar la iteración. Al recibir esta excepción, el código " "del generador debe lanzar :exc:`GeneratorExit` o :exc:`StopIteration`; " "capturar la excepción y hacer cualquier otra cosa es ilegal y disparará un :" "exc:`RuntimeError`. :meth:`~generator.close` también se llamará por el " "recolector de basura de Python cuando se recolecte el generador." #: ../Doc/howto/functional.rst:611 msgid "" "If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I " "suggest using a ``try: ... finally:`` suite instead of catching :exc:" "`GeneratorExit`." msgstr "" "Si necesita ejecutar un código de limpieza cuando ocurre un :exc:" "`GeneratorExit`, sugiero usar un ``try: ... finally:`` en lugar de capturar :" "exc:`GeneratorExit`." #: ../Doc/howto/functional.rst:614 msgid "" "The cumulative effect of these changes is to turn generators from one-way " "producers of information into both producers and consumers." msgstr "" "El efecto acumulativo de estos cambios es convertir a los generadores de " "productores de información unidireccionales en productores y consumidores." #: ../Doc/howto/functional.rst:617 msgid "" "Generators also become **coroutines**, a more generalized form of " "subroutines. Subroutines are entered at one point and exited at another " "point (the top of the function, and a ``return`` statement), but coroutines " "can be entered, exited, and resumed at many different points (the ``yield`` " "statements)." msgstr "" "Los generadores también se convierten en **corrutinas**, una forma más " "generalizada de subrutinas. Las subrutinas inician en un punto y salen en " "otro punto (el inicio de la función, y la sentencia ``return``), pero las " "corrutinas pueden iniciar, salir, y reanudarse en muchos puntos diferentes " "(las sentencias ``yield``)." #: ../Doc/howto/functional.rst:624 msgid "Built-in functions" msgstr "Funciones incorporadas" #: ../Doc/howto/functional.rst:626 msgid "" "Let's look in more detail at built-in functions often used with iterators." msgstr "" "Veamos con más detalle las funciones incorporadas usadas a menudo con " "iteradores." #: ../Doc/howto/functional.rst:628 msgid "" "Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate " "the features of generator expressions:" msgstr "" "Dos de las funciones incorporadas de Python, :func:`map` y :func:`filter` " "duplican las características de las expresiones generadoras:" #: ../Doc/howto/functional.rst:640 msgid "" ":func:`map(f, iterA, iterB, ...) ` returns an iterator over the sequence" msgstr "" ":func:`map(f, iterA, iterB, ...) ` retorna un iterador sobre la " "secuencia" #: ../Doc/howto/functional.rst:632 msgid "" "``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``." msgstr "" "``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``." #: ../Doc/howto/functional.rst:642 msgid "You can of course achieve the same effect with a list comprehension." msgstr "" "Por supuesto puede lograr el mismo efecto con una lista por comprensión." #: ../Doc/howto/functional.rst:644 msgid "" ":func:`filter(predicate, iter) ` returns an iterator over all the " "sequence elements that meet a certain condition, and is similarly duplicated " "by list comprehensions. A **predicate** is a function that returns the " "truth value of some condition; for use with :func:`filter`, the predicate " "must take a single value." msgstr "" ":func:`filter(predicate, iter) ` retorna un iterador sobre todos los " "elementos de la secuencia que reúnen cierta condición, y de forma similar " "está duplicado por las listas por comprensión. Un **predicado** es una " "función que retorna un valor de verdad de alguna condición; para usarlo con :" "func:`filter`, el predicado debe recibir un solo valor." #: ../Doc/howto/functional.rst:657 msgid "This can also be written as a list comprehension:" msgstr "Esto también se puede escribir como una lista por comprensión:" #: ../Doc/howto/functional.rst:663 msgid "" ":func:`enumerate(iter, start=0) ` counts off the elements in the " "iterable returning 2-tuples containing the count (from *start*) and each " "element. ::" msgstr "" ":func:`enumerate(iter, start=0) ` enumera los elementos en el " "iterable retornando 2-tuplas que contienen la enumeración (desde *start*) y " "cada elemento. ::" #: ../Doc/howto/functional.rst:673 msgid "" ":func:`enumerate` is often used when looping through a list and recording " "the indexes at which certain conditions are met::" msgstr "" ":func:`enumerate` a menudo se usa cuando se recorre una lista y se registran " "los índices en los que se reúnen una cierta condición::" #: ../Doc/howto/functional.rst:681 msgid "" ":func:`sorted(iterable, key=None, reverse=False) ` collects all the " "elements of the iterable into a list, sorts the list, and returns the sorted " "result. The *key* and *reverse* arguments are passed through to the " "constructed list's :meth:`~list.sort` method. ::" msgstr "" ":func:`sorted(iterable, key=None, reverse=False) ` reúne todos los " "elementos de un iterable en una lista, ordena la lista, y retorna el " "resultado ordenado. Los argumentos *key* y *reverse* se pasan a través del " "método :meth:`~list.sort` de la lista construida. ::" #: ../Doc/howto/functional.rst:696 msgid "" "(For a more detailed discussion of sorting, see the :ref:`sortinghowto`.)" msgstr "" "(Para un tratamiento más detallado del ordenamiento, ver :ref:" "`sortinghowto`.)" #: ../Doc/howto/functional.rst:699 msgid "" "The :func:`any(iter) ` and :func:`all(iter) ` built-ins look at " "the truth values of an iterable's contents. :func:`any` returns ``True`` if " "any element in the iterable is a true value, and :func:`all` returns " "``True`` if all of the elements are true values:" msgstr "" "Las funciones incorporadas :func:`any(iter) ` y :func:`all(iter) ` " "ven los valores de verdad de los contenidos de un iterable. :func:`any` " "retorna ``True`` si algún elemento en el iterable es un valor verdadero, y :" "func:`all` retorna ``True`` si todos los elementos son valores verdaderos:" #: ../Doc/howto/functional.rst:718 msgid "" ":func:`zip(iterA, iterB, ...) ` takes one element from each iterable " "and returns them in a tuple::" msgstr "" ":func:`zip(iterA, iterB, ...) ` toma un elemento de cada iterable y los " "retorna en una tupla::" #: ../Doc/howto/functional.rst:724 msgid "" "It doesn't construct an in-memory list and exhaust all the input iterators " "before returning; instead tuples are constructed and returned only if " "they're requested. (The technical term for this behaviour is `lazy " "evaluation `__.)" msgstr "" "Esto no construye una lista en memoria y consume todos los iteradores de " "entrada antes de ejecutar; en lugar de eso, las tuplas se construyen y " "retornan solo si son requeridas. (El término técnico para este " "comportamiento es `evaluación perezosa `__.)" #: ../Doc/howto/functional.rst:729 msgid "" "This iterator is intended to be used with iterables that are all of the same " "length. If the iterables are of different lengths, the resulting stream " "will be the same length as the shortest iterable. ::" msgstr "" "Se pretende que el iterador se use con iterables que tengan todos la misma " "longitud. Si los iterables son de diferentes longitudes, el flujo resultante " "tendrá la misma longitud que el iterable más corto. ::" #: ../Doc/howto/functional.rst:736 msgid "" "You should avoid doing this, though, because an element may be taken from " "the longer iterators and discarded. This means you can't go on to use the " "iterators further because you risk skipping a discarded element." msgstr "" "Sin embargo, debería evitar hacer esto, porque se puede tomar un elemento de " "los iteradores más largos y descartarlo. Esto significa que ya no puede " "seguir usando los iteradores porque corre el riesgo de saltarse un elemento " "descartado." #: ../Doc/howto/functional.rst:742 msgid "The itertools module" msgstr "El módulo itertools" #: ../Doc/howto/functional.rst:744 #, fuzzy msgid "" "The :mod:`itertools` module contains a number of commonly used iterators as " "well as functions for combining several iterators. This section will " "introduce the module's contents by showing small examples." msgstr "" "El módulo :mod:`itertools` contiene un número de iteradores comúnmente " "usados así como funciones para combinar varios iteradores. Esta sección " "presentará los contenidos del módulo mostrando pequeños ejemplos." #: ../Doc/howto/functional.rst:748 msgid "The module's functions fall into a few broad classes:" msgstr "Las funciones del módulo caen en unas pocas clases generales:" #: ../Doc/howto/functional.rst:750 msgid "Functions that create a new iterator based on an existing iterator." msgstr "Funciones que crean un nuevo iterador basado en un iterador existente." #: ../Doc/howto/functional.rst:751 msgid "Functions for treating an iterator's elements as function arguments." msgstr "" "Funciones para tratar los elementos de un iterador como argumentos de " "función." #: ../Doc/howto/functional.rst:752 msgid "Functions for selecting portions of an iterator's output." msgstr "Funciones para seleccionar porciones de la salida de un iterador." #: ../Doc/howto/functional.rst:753 msgid "A function for grouping an iterator's output." msgstr "Una función para agrupar la salida de un iterador." #: ../Doc/howto/functional.rst:756 msgid "Creating new iterators" msgstr "Crear nuevos iteradores" #: ../Doc/howto/functional.rst:758 msgid "" ":func:`itertools.count(start, step) ` returns an infinite " "stream of evenly spaced values. You can optionally supply the starting " "number, which defaults to 0, and the interval between numbers, which " "defaults to 1::" msgstr "" ":func:`itertools.count(start, step) ` retorna un flujo " "infinito de valores equiespaciados. Opcionalmente puede suministrar el " "número de inicio, que por defecto es 0, y el intervalo entre números, que " "por defecto es 1::" #: ../Doc/howto/functional.rst:769 msgid "" ":func:`itertools.cycle(iter) ` saves a copy of the contents " "of a provided iterable and returns a new iterator that returns its elements " "from first to last. The new iterator will repeat these elements " "infinitely. ::" msgstr "" ":func:`itertools.cycle(iter) ` guarda una copia de los " "contenidos de un iterable provisto y retorna un nuevo iterador que retorna " "sus elementos del primero al último. El nuevo iterador repetirá estos " "elementos infinitamente. ::" #: ../Doc/howto/functional.rst:776 msgid "" ":func:`itertools.repeat(elem, [n]) ` returns the provided " "element *n* times, or returns the element endlessly if *n* is not " "provided. ::" msgstr "" ":func:`itertools.repeat(elem, [n]) ` retorna el elemento " "provisto *n* veces, o retorna el elemento indefinidamente si no se provee " "*n*. ::" #: ../Doc/howto/functional.rst:784 msgid "" ":func:`itertools.chain(iterA, iterB, ...) ` takes an " "arbitrary number of iterables as input, and returns all the elements of the " "first iterator, then all the elements of the second, and so on, until all of " "the iterables have been exhausted. ::" msgstr "" ":func:`itertools.chain(iterA, iterB, ...) ` recibe un " "número arbitrario de iterables como entrada, y retorna todos los elementos " "del primer iterador, luego todos los elementos del segundo, y así " "sucesivamente, hasta que hayan sido agotados todos los iterables. ::" #: ../Doc/howto/functional.rst:792 msgid "" ":func:`itertools.islice(iter, [start], stop, [step]) ` " "returns a stream that's a slice of the iterator. With a single *stop* " "argument, it will return the first *stop* elements. If you supply a " "starting index, you'll get *stop-start* elements, and if you supply a value " "for *step*, elements will be skipped accordingly. Unlike Python's string " "and list slicing, you can't use negative values for *start*, *stop*, or " "*step*. ::" msgstr "" ":func:`itertools.islice(iter, [start], stop, [step]) ` " "retorna un flujo que es un segmento del iterador. Con solo un argumento " "*stop*, retornará los primeros *stop* elementos. Si suministra un índice de " "inicio, obtendrá los elementos *stop-start*, y si suministra un valor para " "*step*, los elementos se saltarán en consecuencia. A diferencia de la " "segmentación de listas y cadenas de caracteres de Python, no puede usar " "valores negativos para *start*, *stop* o *step*. ::" #: ../Doc/howto/functional.rst:806 msgid "" ":func:`itertools.tee(iter, [n]) ` replicates an iterator; it " "returns *n* independent iterators that will all return the contents of the " "source iterator. If you don't supply a value for *n*, the default is 2. " "Replicating iterators requires saving some of the contents of the source " "iterator, so this can consume significant memory if the iterator is large " "and one of the new iterators is consumed more than the others. ::" msgstr "" ":func:`itertools.tee(iter, [n]) ` replica un iterador; " "retorna *n* iteradores independientes que retornarán los contenidos del " "iterador fuente. Si no suministra un valor para *n*, por defecto es 2. " "Replicar iteradores requiere guardar algunos de los contenidos del iterador " "fuente, esto puede consumir memoria significativa si el iterador es grande y " "uno de los nuevos iteradores se consume más que los otros. ::" #: ../Doc/howto/functional.rst:825 msgid "Calling functions on elements" msgstr "Aplicar funciones a los elementos" #: ../Doc/howto/functional.rst:827 msgid "" "The :mod:`operator` module contains a set of functions corresponding to " "Python's operators. Some examples are :func:`operator.add(a, b) ` (adds two values), :func:`operator.ne(a, b) ` (same as " "``a != b``), and :func:`operator.attrgetter('id') ` " "(returns a callable that fetches the ``.id`` attribute)." msgstr "" "El módulo :mod:`operator` contiene un conjunto de funciones correspondientes " "a los operadores de Python. Algunos ejemplos son :func:`operator.add(a, b) " "` (suma dos valores), :func:`operator.ne(a, b) ` " "(lo mismo que ``a != b``) y :func:`operator.attrgetter('id') ` (retorna un invocable que obtiene el atributo ``.id``)." #: ../Doc/howto/functional.rst:833 msgid "" ":func:`itertools.starmap(func, iter) ` assumes that the " "iterable will return a stream of tuples, and calls *func* using these tuples " "as the arguments::" msgstr "" ":func:`itertools.starmap(func, iter) ` asume que el " "iterable retornará un flujo de tuplas, y llama a *func* usando estas tuplas " "como los argumentos::" #: ../Doc/howto/functional.rst:845 msgid "Selecting elements" msgstr "Seleccionar elementos" #: ../Doc/howto/functional.rst:847 msgid "" "Another group of functions chooses a subset of an iterator's elements based " "on a predicate." msgstr "" "Otro grupo de funciones elige un subconjunto de elementos de un iterador " "basado en un predicado dado." #: ../Doc/howto/functional.rst:850 msgid "" ":func:`itertools.filterfalse(predicate, iter) ` is " "the opposite of :func:`filter`, returning all elements for which the " "predicate returns false::" msgstr "" ":func:`itertools.filterfalse(predicate, iter) ` es el " "opuesto de :func:`filter`, retornando todos los elementos para los que el " "predicado retorna falso::" #: ../Doc/howto/functional.rst:857 msgid "" ":func:`itertools.takewhile(predicate, iter) ` returns " "elements for as long as the predicate returns true. Once the predicate " "returns false, the iterator will signal the end of its results. ::" msgstr "" ":func:`itertools.takewhile(predicate, iter) ` retorna " "los elementos mientras el predicado retorne verdadero. Una vez que el " "predicado retorna falso, el iterador indicará el final de sus resultados. ::" #: ../Doc/howto/functional.rst:870 msgid "" ":func:`itertools.dropwhile(predicate, iter) ` discards " "elements while the predicate returns true, and then returns the rest of the " "iterable's results. ::" msgstr "" ":func:`itertools.dropwhile(predicate, iter) ` descarta " "los elementos mientras el predicado retorne verdadero, y luego retorna el " "resto de los resultados del iterable. ::" #: ../Doc/howto/functional.rst:880 msgid "" ":func:`itertools.compress(data, selectors) ` takes two " "iterators and returns only those elements of *data* for which the " "corresponding element of *selectors* is true, stopping whenever either one " "is exhausted::" msgstr "" ":func:`itertools.compress(data, selectors) ` recibe dos " "iteradores y retorna solo aquellos elementos de *data* para los cuales el " "elemento correspondiente de *selectors* es verdadero, deteniéndose cuando " "alguno se termine::" #: ../Doc/howto/functional.rst:889 msgid "Combinatoric functions" msgstr "Funciones combinatorias" #: ../Doc/howto/functional.rst:891 msgid "" "The :func:`itertools.combinations(iterable, r) ` " "returns an iterator giving all possible *r*-tuple combinations of the " "elements contained in *iterable*. ::" msgstr "" "La función :func:`itertools.combinations(iterable, r) ` retorna un iterador proporcionando todas las combinaciones de " "*r*-tuplas de los elementos contenidos en *iterable*. ::" #: ../Doc/howto/functional.rst:906 msgid "" "The elements within each tuple remain in the same order as *iterable* " "returned them. For example, the number 1 is always before 2, 3, 4, or 5 in " "the examples above. A similar function, :func:`itertools." "permutations(iterable, r=None) `, removes this " "constraint on the order, returning all possible arrangements of length *r*::" msgstr "" "Los elementos dentro de cada tupla permanecen en el mismo orden en el que " "*iterable* los retornó. Por ejemplo, el número 1 siempre está antes que 2, " "3, 4 o 5 en los ejemplos de arriba. Una función similar, :func:`itertools." "permutations(iterable, r=None) `, remueve esta " "restricción en el orden, retornando todas las disposiciones posibles de " "longitud *r*::" #: ../Doc/howto/functional.rst:925 msgid "" "If you don't supply a value for *r* the length of the iterable is used, " "meaning that all the elements are permuted." msgstr "" "Si no suministra un valor para *r* se usa la longitud del iterable, lo que " "significa que se permutan todos los elementos." #: ../Doc/howto/functional.rst:928 msgid "" "Note that these functions produce all of the possible combinations by " "position and don't require that the contents of *iterable* are unique::" msgstr "" "Note que estas funciones producen todas las combinaciones posibles por " "posición y no requieren que los contenidos de *iterable* sean únicos::" #: ../Doc/howto/functional.rst:935 msgid "" "The identical tuple ``('a', 'a', 'b')`` occurs twice, but the two 'a' " "strings came from different positions." msgstr "" "La tupla idéntica ``('a', 'a', 'b')`` aparece dos veces, pero las dos " "cadenas de caracteres 'a' provienen de diferentes posiciones." #: ../Doc/howto/functional.rst:938 msgid "" "The :func:`itertools.combinations_with_replacement(iterable, r) ` function relaxes a different constraint: " "elements can be repeated within a single tuple. Conceptually an element is " "selected for the first position of each tuple and then is replaced before " "the second element is selected. ::" msgstr "" "La función :func:`itertools.combinations_with_replacement(iterable, r) " "` relaja una restricción diferente: " "los elementos se pueden repetir dentro de una misma tupla. Conceptualmente " "un elemento se elige para la primera posición de cada tupla y luego se " "reemplaza antes de que se elija el segundo elemento. ::" #: ../Doc/howto/functional.rst:953 msgid "Grouping elements" msgstr "Agrupar elementos" #: ../Doc/howto/functional.rst:955 msgid "" "The last function I'll discuss, :func:`itertools.groupby(iter, " "key_func=None) `, is the most complicated. " "``key_func(elem)`` is a function that can compute a key value for each " "element returned by the iterable. If you don't supply a key function, the " "key is simply each element itself." msgstr "" "La última función que trataré, :func:`itertools.groupby(iter, key_func=None) " "`, es la más complicada. ``key_func(elem)`` es una " "función que calcula un valor clave para cada elemento retornado por el " "iterable. Si no suministra una función de clave, la clave será simplemente " "el elemento mismo." #: ../Doc/howto/functional.rst:960 msgid "" ":func:`~itertools.groupby` collects all the consecutive elements from the " "underlying iterable that have the same key value, and returns a stream of 2-" "tuples containing a key value and an iterator for the elements with that key." msgstr "" ":func:`~itertools.groupby` reúne todos los elementos consecutivos del " "iterable subyacente que tienen el mismo valor clave, y retorna un flujo de 2-" "tuplas que contienen un valor clave y un iterador para los elementos con esa " "clave." #: ../Doc/howto/functional.rst:988 msgid "" ":func:`~itertools.groupby` assumes that the underlying iterable's contents " "will already be sorted based on the key. Note that the returned iterators " "also use the underlying iterable, so you have to consume the results of " "iterator-1 before requesting iterator-2 and its corresponding key." msgstr "" ":func:`~itertools.groupby` asume que los contenidos del iterable subyacente " "ya se ordenó basado en la clave. Note que los iteradores retornados también " "usan el iterable subyacente, así que tiene que consumir los resultados de " "iterador-1 antes de solicitar iterador-2 y su clave correspondiente." #: ../Doc/howto/functional.rst:995 msgid "The functools module" msgstr "El módulo functools" #: ../Doc/howto/functional.rst:997 msgid "" "The :mod:`functools` module in Python 2.5 contains some higher-order " "functions. A **higher-order function** takes one or more functions as input " "and returns a new function. The most useful tool in this module is the :" "func:`functools.partial` function." msgstr "" "El módulo :mod:`functools` en Python 2.5 contiene algunas funciones de orden " "superior. Una **función de orden superior** recibe una o más funciones como " "entrada y retorna una nueva función. La herramienta más útil en este módulo " "es la función :func:`functools.partial`." #: ../Doc/howto/functional.rst:1002 msgid "" "For programs written in a functional style, you'll sometimes want to " "construct variants of existing functions that have some of the parameters " "filled in. Consider a Python function ``f(a, b, c)``; you may wish to create " "a new function ``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're " "filling in a value for one of ``f()``'s parameters. This is called " "\"partial function application\"." msgstr "" "Para programas escritos en un estilo funcional, a veces querrá construir " "variantes de funciones existentes que tienen algunos de los parámetros " "predefinidos. Considere una función de Python ``f(a, b, c)``; puede querer " "crear una nueva función ``g(b, c)`` que sea equivalente a ``f(1, b, c)``; " "está completando un valor para uno de los parámetros de ``f()``. Esto se " "llama \"aplicación parcial de funciones\"." #: ../Doc/howto/functional.rst:1008 msgid "" "The constructor for :func:`~functools.partial` takes the arguments " "``(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)``. The " "resulting object is callable, so you can just call it to invoke ``function`` " "with the filled-in arguments." msgstr "" "El constructor para :func:`~functools.partial` recibe los argumentos " "``(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)``. El objeto " "resultante es invocable, por lo que puede invocar a ``function`` con los " "argumentos rellenados." #: ../Doc/howto/functional.rst:1013 msgid "Here's a small but realistic example::" msgstr "Aquí hay un ejemplo pequeño pero realista::" #: ../Doc/howto/functional.rst:1025 msgid "" ":func:`functools.reduce(func, iter, [initial_value]) ` " "cumulatively performs an operation on all the iterable's elements and, " "therefore, can't be applied to infinite iterables. *func* must be a function " "that takes two elements and returns a single value. :func:`functools." "reduce` takes the first two elements A and B returned by the iterator and " "calculates ``func(A, B)``. It then requests the third element, C, " "calculates ``func(func(A, B), C)``, combines this result with the fourth " "element returned, and continues until the iterable is exhausted. If the " "iterable returns no values at all, a :exc:`TypeError` exception is raised. " "If the initial value is supplied, it's used as a starting point and " "``func(initial_value, A)`` is the first calculation. ::" msgstr "" ":func:`functools.reduce(func, iter, [initial_value]) ` " "realiza acumulativamente una operación en todos los elementos del iterable " "y, por lo tanto, no se puede aplicar a infinitos iterables. *func* debe ser " "una función que recibe dos elementos y retorna un solo valor. :func:" "`functools.reduce` recibe los primeros dos elementos A y B retornados por el " "iterador y calcula ``func(A, B)``. Luego pide el tercer elemento, C, calcula " "``func(func(A, B), C)``, combina este resultado con el cuarto elemento " "retornado, y continua hasta que se agote el iterable. Si el iterable no " "retorna ningún valor, se lanza una excepción :exc:`TypeError`. Si se " "suministra el valor inicial, se usa como punto inicial y " "``func(initial_value, A)`` es el primer cálculo. ::" #: ../Doc/howto/functional.rst:1049 msgid "" "If you use :func:`operator.add` with :func:`functools.reduce`, you'll add up " "all the elements of the iterable. This case is so common that there's a " "special built-in called :func:`sum` to compute it:" msgstr "" "Si usa :func:`operator.add` con :func:`functools.reduce`, sumará todos los " "elementos del iterable. Este caso es tan común que hay una función " "incorporada especial llamada :func:`sum` para calcularla:" #: ../Doc/howto/functional.rst:1061 msgid "" "For many uses of :func:`functools.reduce`, though, it can be clearer to just " "write the obvious :keyword:`for` loop::" msgstr "" "Sin embargo, para muchos usos de :func:`functools.reduce` puede ser mas " "claro simplemente escribir el ciclo :keyword:`for`::" #: ../Doc/howto/functional.rst:1073 msgid "" "A related function is :func:`itertools.accumulate(iterable, func=operator." "add) `. It performs the same calculation, but instead " "of returning only the final result, :func:`accumulate` returns an iterator " "that also yields each partial result::" msgstr "" "Una función relacionada es :func:`itertools.accumulate(iterable, " "func=operator.add) `. Realiza el mismo cálculo, pero " "en lugar de retornar solo el resultado final, :func:`accumulate` retorna un " "iterador que también produce cada resultado parcial::" #: ../Doc/howto/functional.rst:1086 msgid "The operator module" msgstr "El módulo operator" #: ../Doc/howto/functional.rst:1088 msgid "" "The :mod:`operator` module was mentioned earlier. It contains a set of " "functions corresponding to Python's operators. These functions are often " "useful in functional-style code because they save you from writing trivial " "functions that perform a single operation." msgstr "" "El módulo :mod:`operator` se mencionó anteriormente. Contiene un conjunto de " "funciones que corresponden a los operadores de Python. Estas funciones a " "menudo son útiles en código en estilo funcional porque le salvan de escribir " "funciones triviales que realizan una sola operación." #: ../Doc/howto/functional.rst:1093 msgid "Some of the functions in this module are:" msgstr "Algunas de las funciones en este módulo son:" #: ../Doc/howto/functional.rst:1095 msgid "" "Math operations: ``add()``, ``sub()``, ``mul()``, ``floordiv()``, " "``abs()``, ..." msgstr "" "Operaciones matemáticas: ``add()``, ``sub()``, ``mul()``, ``floordiv()``, " "``abs()``, ..." #: ../Doc/howto/functional.rst:1096 msgid "Logical operations: ``not_()``, ``truth()``." msgstr "Operaciones lógicas: ``not_()``, ``truth()``." #: ../Doc/howto/functional.rst:1097 msgid "Bitwise operations: ``and_()``, ``or_()``, ``invert()``." msgstr "Operaciones bit a bit: ``and_()``, ``or_()``, ``invert()``." #: ../Doc/howto/functional.rst:1098 msgid "" "Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``." msgstr "" "Comparaciones: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()`` y ``ge()``." #: ../Doc/howto/functional.rst:1099 msgid "Object identity: ``is_()``, ``is_not()``." msgstr "Identidad de objeto: ``is_()``, ``is_not()``." #: ../Doc/howto/functional.rst:1101 msgid "Consult the operator module's documentation for a complete list." msgstr "Consulte la documentación del módulo operator para una lista completa." #: ../Doc/howto/functional.rst:1105 msgid "Small functions and the lambda expression" msgstr "Funciones pequeñas y la expresión lambda" #: ../Doc/howto/functional.rst:1107 msgid "" "When writing functional-style programs, you'll often need little functions " "that act as predicates or that combine elements in some way." msgstr "" "Cuando se escriben programas en estilo funcional, a menudo necesitará " "pequeñas funciones que actúen como predicados o que combinen elementos de " "alguna manera." #: ../Doc/howto/functional.rst:1110 msgid "" "If there's a Python built-in or a module function that's suitable, you don't " "need to define a new function at all::" msgstr "" "Si hay una función incorporada o un módulo de Python, no necesita definir " "una nueva función en absoluto::" #: ../Doc/howto/functional.rst:1116 msgid "" "If the function you need doesn't exist, you need to write it. One way to " "write small functions is to use the :keyword:`lambda` expression. " "``lambda`` takes a number of parameters and an expression combining these " "parameters, and creates an anonymous function that returns the value of the " "expression::" msgstr "" "Si la función que necesita no existe, necesita escribirla. Una forma de " "escribir funciones pequeñas es usar la expresión :keyword:`lambda`. " "``lambda`` recibe un número de parámetros y una expresión que combina estos " "parámetros, y crea una función anónima que retorna el valor de la expresión::" #: ../Doc/howto/functional.rst:1125 msgid "" "An alternative is to just use the ``def`` statement and define a function in " "the usual way::" msgstr "" "Una alternativa es simplemente usar la sentencia ``def`` y definir una " "función en la forma usual::" #: ../Doc/howto/functional.rst:1134 msgid "" "Which alternative is preferable? That's a style question; my usual course " "is to avoid using ``lambda``." msgstr "" "¿Qué alternativa es preferible? Esa es una pregunta de estilo; mi rumbo " "usual es evitar usar ``lambda``." #: ../Doc/howto/functional.rst:1137 msgid "" "One reason for my preference is that ``lambda`` is quite limited in the " "functions it can define. The result has to be computable as a single " "expression, which means you can't have multiway ``if... elif... else`` " "comparisons or ``try... except`` statements. If you try to do too much in a " "``lambda`` statement, you'll end up with an overly complicated expression " "that's hard to read. Quick, what's the following code doing? ::" msgstr "" "Una razón para mi preferencia es que ``lambda`` es muy limitado en las " "funciones que puede definir. El resultado tiene que ser calculable como una " "sola expresión, que significa que no tiene comparaciones multivía ``if... " "elif... else`` o sentencias ``try... except``. Si intenta hacer mucho en una " "sentencia ``lambda``, terminará con una expresión demasiado complicada que " "es difícil de leer. Rápido, ¿qué hace el siguiente código? ::" #: ../Doc/howto/functional.rst:1147 msgid "" "You can figure it out, but it takes time to disentangle the expression to " "figure out what's going on. Using a short nested ``def`` statements makes " "things a little bit better::" msgstr "" "Puede averiguarlo, pero toma tiempo desenredar la expresión para averiguar " "que está pasando. Usar una corta sentencia ``def`` anidada hace las cosas un " "poco mejor::" #: ../Doc/howto/functional.rst:1157 msgid "But it would be best of all if I had simply used a ``for`` loop::" msgstr "" "Pero lo mejor de todo sería si simplemente hubiese usado un ciclo ``for``::" #: ../Doc/howto/functional.rst:1163 msgid "Or the :func:`sum` built-in and a generator expression::" msgstr "O la función incorporada :func:`sum` y una expresión generadora::" #: ../Doc/howto/functional.rst:1167 msgid "" "Many uses of :func:`functools.reduce` are clearer when written as ``for`` " "loops." msgstr "" "Muchos usos de :func:`functools.reduce` son más claros cuando se escriben " "como ciclos ``for``." #: ../Doc/howto/functional.rst:1169 msgid "" "Fredrik Lundh once suggested the following set of rules for refactoring uses " "of ``lambda``:" msgstr "" "Fredrik Lundh una vez sugirió el siguiente conjunto de reglas para " "refactorizar los usos de ``lambda``:" #: ../Doc/howto/functional.rst:1172 msgid "Write a lambda function." msgstr "Escribir una función lambda." #: ../Doc/howto/functional.rst:1173 msgid "Write a comment explaining what the heck that lambda does." msgstr "Escribir un comentario explicando qué demonios hace esa lambda." #: ../Doc/howto/functional.rst:1174 msgid "" "Study the comment for a while, and think of a name that captures the essence " "of the comment." msgstr "" "Estudiar el comentario por un momento, y pensar en un nombre que capture la " "esencia del comentario." #: ../Doc/howto/functional.rst:1176 msgid "Convert the lambda to a def statement, using that name." msgstr "Convertir la lambda a una sentencia def, usando ese nombre." #: ../Doc/howto/functional.rst:1177 msgid "Remove the comment." msgstr "Remover el comentario." #: ../Doc/howto/functional.rst:1179 msgid "" "I really like these rules, but you're free to disagree about whether this " "lambda-free style is better." msgstr "" "Me gustan mucho estas reglas, pero es libre de disentir acerca de si este " "estilo libre de lambda es mejor." #: ../Doc/howto/functional.rst:1184 msgid "Revision History and Acknowledgements" msgstr "Historia de revisiones y reconocimientos" #: ../Doc/howto/functional.rst:1186 msgid "" "The author would like to thank the following people for offering " "suggestions, corrections and assistance with various drafts of this article: " "Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike " "Krell, Leandro Lameiro, Jussi Salmela, Collin Winter, Blake Winton." msgstr "" "Al autor le gustaría agradecer a las siguientes personar por ofrecer " "sugerencias, correcciones y asistencia con varios borradores de este " "articulo: Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger, Jim " "Jewett, Mike Krell, Leandro Lameiro, Jussi Salmela, Collin Winter, Blake " "Winton." #: ../Doc/howto/functional.rst:1191 msgid "Version 0.1: posted June 30 2006." msgstr "Versión 0.1: publicada el 30 de junio de 2006." #: ../Doc/howto/functional.rst:1193 msgid "Version 0.11: posted July 1 2006. Typo fixes." msgstr "" "Versión 0.11: publicada el 1 de julio de 2006. Errores tipográficos " "arreglados." #: ../Doc/howto/functional.rst:1195 msgid "" "Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into " "one. Typo fixes." msgstr "" "Versión 0.2: publicada el 10 de julio de 2006. Secciones genexp y listcomp " "unidas en una sola. Errores tipográficos arreglados." #: ../Doc/howto/functional.rst:1198 msgid "" "Version 0.21: Added more references suggested on the tutor mailing list." msgstr "" "Versión 0.21: Agregadas mas referencias sugeridas en la lista de correos " "tutor." #: ../Doc/howto/functional.rst:1200 msgid "" "Version 0.30: Adds a section on the ``functional`` module written by Collin " "Winter; adds short section on the operator module; a few other edits." msgstr "" "Versión 0.30: Agrega una sección sobre el módulo ``functional`` escrito por " "Collin Winter; agrega una sección corta sobre el módulo operator; y unas " "pocas otras ediciones." #: ../Doc/howto/functional.rst:1205 msgid "References" msgstr "Referencias" #: ../Doc/howto/functional.rst:1208 msgid "General" msgstr "Generales" #: ../Doc/howto/functional.rst:1210 msgid "" "**Structure and Interpretation of Computer Programs**, by Harold Abelson and " "Gerald Jay Sussman with Julie Sussman. Full text at https://mitpress.mit." "edu/sicp/. In this classic textbook of computer science, chapters 2 and 3 " "discuss the use of sequences and streams to organize the data flow inside a " "program. The book uses Scheme for its examples, but many of the design " "approaches described in these chapters are applicable to functional-style " "Python code." msgstr "" "**Estructura e interpretación de programas de computadora**, por Harold " "Abelson y Gerald Jay Sussman con Julie Sussman. Texto completo en https://" "mitpress.mit.edu/sicp/. En este libro clásico de ciencia de computación, los " "capítulos 2 y 3 tratan el uso de secuencias y flujos para organizar el flujo " "de datos dentro de un programa. El libro usa Scheme para sus ejemplos, pero " "muchos de los enfoques de diseño descritos en estos capítulos son aplicables " "al código de Python en estilo funcional." #: ../Doc/howto/functional.rst:1218 #, fuzzy msgid "" "https://www.defmacro.org/ramblings/fp.html: A general introduction to " "functional programming that uses Java examples and has a lengthy historical " "introduction." msgstr "" "http://www.defmacro.org/ramblings/fp.html: Una introducción general a la " "programación funcional que usa ejemplos en Java y tiene una introducción " "histórica extensa." #: ../Doc/howto/functional.rst:1221 msgid "" "https://en.wikipedia.org/wiki/Functional_programming: General Wikipedia " "entry describing functional programming." msgstr "" "https://es.wikipedia.org/wiki/Programaci%C3%B3n_funcional: Entrada general " "de Wikipedia que describe la programación funcional." #: ../Doc/howto/functional.rst:1224 msgid "https://en.wikipedia.org/wiki/Coroutine: Entry for coroutines." msgstr "https://es.wikipedia.org/wiki/Corrutina: Entrada para corrutinas." #: ../Doc/howto/functional.rst:1226 msgid "" "https://en.wikipedia.org/wiki/Currying: Entry for the concept of currying." msgstr "" "https://es.wikipedia.org/wiki/Currificaci%C3%B3n: Entrada para el concepto " "de currificación." #: ../Doc/howto/functional.rst:1229 msgid "Python-specific" msgstr "Específicas de Python" #: ../Doc/howto/functional.rst:1231 #, fuzzy msgid "" "https://gnosis.cx/TPiP/: The first chapter of David Mertz's book :title-" "reference:`Text Processing in Python` discusses functional programming for " "text processing, in the section titled \"Utilizing Higher-Order Functions in " "Text Processing\"." msgstr "" "http://gnosis.cx/TPiP/: El primer capítulo del libro de David Mertz :title-" "reference:`Text Processing in Python` trata la programación funcional para " "procesamiento de texto, en la sección titulada \"Utilizando funciones de " "orden superior en procesamiento de texto\"." #: ../Doc/howto/functional.rst:1236 msgid "" "Mertz also wrote a 3-part series of articles on functional programming for " "IBM's DeveloperWorks site; see `part 1 `__, `part 2 `__, and " "`part 3 `__," msgstr "" "Mertz también escribió una serie de artículos de 3 partes sobre programación " "funcional para el sitio DeveloperWorks de IBM; ver `parte 1 `__, `parte 2 `__, y `parte 3 `__," #: ../Doc/howto/functional.rst:1244 msgid "Python documentation" msgstr "Documentación de Python" #: ../Doc/howto/functional.rst:1246 msgid "Documentation for the :mod:`itertools` module." msgstr "Documentación del módulo :mod:`itertools`." #: ../Doc/howto/functional.rst:1248 msgid "Documentation for the :mod:`functools` module." msgstr "Documentación del módulo :mod:`functools`." #: ../Doc/howto/functional.rst:1250 msgid "Documentation for the :mod:`operator` module." msgstr "Documentación del módulo :mod:`operator`." #: ../Doc/howto/functional.rst:1252 msgid ":pep:`289`: \"Generator Expressions\"" msgstr ":pep:`289`: \"Expresiones generadoras\"" #: ../Doc/howto/functional.rst:1254 msgid "" ":pep:`342`: \"Coroutines via Enhanced Generators\" describes the new " "generator features in Python 2.5." msgstr "" ":pep:`342`: \"Corrutinas a través de generadores mejorados\" describe las " "características del nuevo generador en Python 2.5."