Changeset 27
- Timestamp:
- 01/07/09 09:05:59 (4 years ago)
- bzr:base-revision:
- svn-v4:35130877-2dc0-4e93-869b-628e2b47754a:trunk:26
- bzr:committer:
- Gonzalo Delgado <gonzalodel@gmail.com>
- bzr:file-ids:
traducidos/datastructures.rst 4@35130877-2dc0-4e93-869b-628e2b47754a:trunk%2Ftraducidos%2Fdatastructures.rst- bzr:mapping-version:
- v4
- bzr:repository-uuid:
- 35130877-2dc0-4e93-869b-628e2b47754a
- bzr:revision-id:
- gonzalodel@gmail.com-20090629200121-hv8fkebgp6n9ebwc
- bzr:revno:
- 27
- bzr:revprop:branch-nick:
- python-tutorial
- bzr:revprop:rebase-of:
- gonzalodel@gmail.com-20090629200121-bge38665yed61bka
- bzr:root:
- trunk
- bzr:text-parents:
traducidos/datastructures.rst svn-v4:35130877-2dc0-4e93-869b-628e2b47754a:trunk:4- bzr:timestamp:
- 2009-06-29 17:01:21.240000010 -0300
- bzr:user-agent:
- bzr1.13.1+bzr-svn0.5.3
- svn:original-date:
- 2009-06-29T20:01:21.240000Z
- File:
-
- 1 edited
-
trunk/traducidos/datastructures.rst (modified) (14 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/traducidos/datastructures.rst
r4 r27 1 1 .. _tut-structures: 2 2 3 *************** 4 Data Structures5 *************** 6 7 This chapter describes some things you've learned about already in more detail,8 and adds some new things as well.3 ******************** 4 Estructuras de datos 5 ******************** 6 7 Este capítulo describe algunas cosas que ya aprendiste en más detalle, 8 y agrega algunas cosas nuevas también. 9 9 10 10 11 11 .. _tut-morelists: 12 12 13 M ore on Lists14 ============= 15 16 The list data type has some more methods. Here are all of the methods of list 17 objects:13 Más sobre listas 14 ================ 15 16 El tipo de dato lista tiene algunos métodos más. Aquí están todos los métodos 17 de los objetos lista: 18 18 19 19 … … 21 21 :noindex: 22 22 23 A dd an item to the end of the list; equivalent to``a[len(a):] = [x]``.23 Agrega un ítem al final de la lista; equivale a ``a[len(a):] = [x]``. 24 24 25 25 … … 27 27 :noindex: 28 28 29 Ext end the list by appending all the items in the given list; equivalent to30 ``a[len(a):] = L``.29 Extiende la lista agregándole todos los ítems de la lista dada; equivale 30 a ``a[len(a):] = L``. 31 31 32 32 … … 34 34 :noindex: 35 35 36 Insert an item at a given position. The first argument is the index of the 37 element before which to insert, so ``a.insert(0, x)`` inserts at the front of 38 the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``. 36 Inserta un ítem en una posición dada. El primer argumento es el índice 37 del ítem delante del cual se insertará, por lo tanto ``a.insert(0, x)`` 38 inserta al principio de la lista, y ``a.insert(len(a), x)`` equivale a 39 ``a.append(x)``. 39 40 40 41 … … 42 43 :noindex: 43 44 44 Remove the first item from the list whose value is *x*. It is an error if there45 is no such item.45 Quita el primer ítem de la lista cuyo calor sea *x*. Es un error si no 46 existe tal ítem. 46 47 47 48 … … 49 50 :noindex: 50 51 51 Remove the item at the given position in the list, and return it. If no index 52 is specified, ``a.pop()`` removes and returns the last item in the list. (The 53 square brackets around the *i* in the method signature denote that the parameter 54 is optional, not that you should type square brackets at that position. You 55 will see this notation frequently in the Python Library Reference.) 52 Quita el ítem en la posición dada de la lista, y lo devuelve. Si no se 53 especifica un índice, ``a.pop()`` quita y devuelve el último ítem de la 54 lista. (Los corchetes que encierran a *i* en la firma del método) denotan 55 que el parámetro es opcional, no que deberías escribir corchetes en esa 56 posición. Verás esta notación con frecuencia en la Referencia de la 57 Biblioteca de Python.) 56 58 57 59 … … 59 61 :noindex: 60 62 61 Return the index in the list of the first item whose value is *x*. It is an 62 error if there is no such item. 63 63 Devuelve el índice en la lista del primer ítem cuyo valor sea *x*. Es un 64 error si no existe tal ítem. 64 65 65 66 .. method:: list.count(x) 66 67 :noindex: 67 68 68 Return the number of times *x* appears in the list.69 Devuelve el número de veces que *x* aparece en la lista. 69 70 70 71 … … 72 73 :noindex: 73 74 74 Sort the items of the list, in place.75 Ordena los ítems de la lista, in situ. 75 76 76 77 … … 78 79 :noindex: 79 80 80 Reverse the elements of the list, in place.81 82 An example that uses most of the list methods::81 Invierte los elementos de la lista, in situ. 82 83 Un ejemplo que usa la mayoría de los métodos de lista:: 83 84 84 85 >>> a = [66.25, 333, 333, 1, 1234.5] … … 104 105 .. _tut-lists-as-stacks: 105 106 106 Us ing Lists as Stacks107 --------------------- 107 Usando listas como pilas 108 ------------------------ 108 109 109 110 .. sectionauthor:: Ka-Ping Yee <ping@lfw.org> 110 111 111 112 112 The list methods make it very easy to use a list as a stack, where the last 113 element added is the first element retrieved ("last-in, first-out"). To add an 114 item to the top of the stack, use :meth:`append`. To retrieve an item from the 115 top of the stack, use :meth:`pop` without an explicit index. For example:: 113 Los métodos de lista hacen que resulte muy fácil usar una lista como una pila, 114 donde el último elemento añadido es el primer elemento retirado ("último en 115 entrar, primero en salir"). Para agregar un ítem a la cima de la pila, use 116 :meth:`append`. Para retirar un ítem de la cima de la pila, use :meth:`pop` 117 sin un índice explícito. Por ejemplo:: 116 118 117 119 >>> stack = [3, 4, 5] … … 134 136 .. _tut-lists-as-queues: 135 137 136 Us ing Lists as Queues137 --------------------- 138 Usando Listas como Filas 139 ------------------------ 138 140 139 141 .. sectionauthor:: Ka-Ping Yee <ping@lfw.org> 140 142 141 143 142 You can also use a list conveniently as a queue, where the first element added 143 is the first element retrieved ("first-in, first-out"). To add an item to the 144 back of the queue, use :meth:`append`. To retrieve an item from the front of 145 the queue, use :meth:`pop` with ``0`` as the index. For example:: 144 También puedes usar una lista convenientemente como una fila, donde el primer 145 elemento añadido es el primer elemento retirado ("primero en entrar, primero 146 en salir"). Para agregar un ítem al final de la fila, use :meth:`append`. 147 Para retirar un ítem del frente de la fila, use :meth:`pop` con ``0`` como 148 índice. Por ejemplo:: 146 149 147 150 >>> queue = ["Eric", "John", "Michael"] 148 >>> queue.append("Terry") # Terry arrives149 >>> queue.append("Graham") # Graham arrives151 >>> queue.append("Terry") # llega Terry 152 >>> queue.append("Graham") # llega Graham 150 153 >>> queue.pop(0) 151 154 'Eric' … … 158 161 .. _tut-functional: 159 162 160 Functional Programming Tools 161 ---------------------------- 162 163 There are three built-in functions that are very useful when used with lists: 164 :func:`filter`, :func:`map`, and :func:`reduce`. 165 166 ``filter(function, sequence)`` returns a sequence consisting of those items from 167 the sequence for which ``function(item)`` is true. If *sequence* is a 168 :class:`string` or :class:`tuple`, the result will be of the same type; 169 otherwise, it is always a :class:`list`. For example, to compute some primes:: 163 Herramientas de Programación Funcional 164 -------------------------------------- 165 166 Hay tres funciones integradas que son muy útiles cuando se usan con listas: 167 :func:`filter`, :func:`map`, y :func:`reduce`. 168 169 ``filter(funcion, secuencia)`` devuelve una secuencia con aquellos ítems de la 170 secuencia para los cuales ``funcion(item)`` es verdadero. Si *secuencia* es una 171 :class:`cadena` o :class:`tupla`, el resultado será del mismo tipo; 172 de otra manera, siempre es una :class:`lista`. Por ejemplo, para calcular unos 173 primos:: 170 174 171 175 >>> def f(x): return x % 2 != 0 and x % 3 != 0 … … 174 178 [5, 7, 11, 13, 17, 19, 23] 175 179 176 ``map(func tion, sequence)`` calls ``function(item)`` for each of the sequence's177 items and returns a list of the return values. For example, to compute some 178 cubes::179 180 >>> def cub e(x): return x*x*x181 ... 182 >>> map(cub e, range(1, 11))180 ``map(funcion, secuencia)`` llama a ``funcion(item)`` por cada uno de los 181 ítems de la secuencia y devuelve una lista de los valores retornados. Por 182 ejemplo, para calcular unos cubos:: 183 184 >>> def cubo(x): return x*x*x 185 ... 186 >>> map(cubo, range(1, 11)) 183 187 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] 184 188 185 More than one sequence may be passed; the function must then have as many 186 argument s as there are sequences and is called with the corresponding item from187 each sequence (or ``None`` if some sequence is shorter than another). For188 e xample::189 190 >>> se q= range(8)189 Se puede pasar más de una secuencia; la función debe entonces tener tantos 190 argumentos como secuencias haya y es llamada con el ítem correspondiente de 191 cada secuencia (o ``None`` si alguna secuencia es más corta que otra). Por 192 ejemplo:: 193 194 >>> sec = range(8) 191 195 >>> def add(x, y): return x+y 192 196 ... 193 >>> map(add, se q, seq)197 >>> map(add, sec, sec) 194 198 [0, 2, 4, 6, 8, 10, 12, 14] 195 199 196 ``reduce(func tion, sequence)`` returns a single value constructed by calling the197 binary function *function* on the first two items of the sequence, then on the 198 result and the next item, and so on. For example, to compute the sum of the 199 numbers 1 through10::200 201 >>> def add(x,y): return x+y202 ... 203 >>> reduce( add, range(1, 11))200 ``reduce(funcion, secuencia)`` devuelve un único valor que se construye 201 llamando a la función binaria *funcion* con los primeros dos ítems de la 202 secuencia, entonces con el resultado y el siguiente ítem, y así sucesivamente. 203 Por ejemplo, para calcular la suma de los números de 1 a 10:: 204 205 >>> def sumar(x,y): return x+y 206 ... 207 >>> reduce(sumar, range(1, 11)) 204 208 55 205 209 206 If there's only one item in the sequence, its value is returned; if the sequence 207 is empty, an exception is raised.208 209 A third argument can be passed to indicate the starting value. In this case the 210 starting value is returned for an empty sequence, and the function is first 211 applied to the starting value and the first sequence item, then to the result 212 and the next item, and so on. For example, ::213 214 >>> def sum(se q):215 ... def add(x,y): return x+y216 ... return reduce( add, seq, 0)210 Si sólo hay un ítem en la secuencia, se devuelve su valor; si la secuencia 211 está vacía, se lanza una excepción. 212 213 Un tercer argumento puede pasarse para indicar el valor inicial. En este caso 214 el valor inicial se devuelve para una secuencia vacía, y la función se aplica 215 primero al valor inicial y el primer ítem de la secuencia, entonces al 216 resultado y al siguiente ítem, y así sucesivamente. Por ejemplo, :: 217 218 >>> def sum(sec): 219 ... def sumar(x,y): return x+y 220 ... return reduce(sumar, sec, 0) 217 221 ... 218 222 >>> sum(range(1, 11)) … … 221 225 0 222 226 223 Don't use this example's definition of :func:`sum`: since summing numbers is 224 such a common need, a built-in function ``sum(sequence)`` is already provided,225 and works exactly like this.227 No uses la definicón de este ejemplo de :func:`sum`: ya que la sumatoria es una 228 necesidad tan común, una función integrada ``sum(secuencia)`` ya es provista, 229 y funciona exactamente así. 226 230 227 231 .. versionadded:: 2.3
Note: See TracChangeset
for help on using the changeset viewer.
![(please configure the [header_logo] section in trac.ini)](/python-tutorial/chrome/site/your_project_logo.png)