-
-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathdatastructures.po
More file actions
867 lines (774 loc) · 40.2 KB
/
Copy pathdatastructures.po
File metadata and controls
867 lines (774 loc) · 40.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
# SOME DESCRIPTIVE TITLE.
# Copyright (C) 1990-2020, Python Software Foundation
# This file is distributed under the same license as the Python package.
#
# Translators:
# Claudio Rogerio Carvalho Filho <excriptbrasil@gmail.com>, 2017
msgid ""
msgstr ""
"Project-Id-Version: Python 2.7\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-02-09 18:46+0900\n"
"PO-Revision-Date: 2019-09-01 05:18+0000\n"
"Last-Translator: Adorilson Bezerra <adorilson@gmail.com>\n"
"Language-Team: Portuguese (Brazil) (http://www.transifex.com/python-doc/python-27/language/pt_BR/)\n"
"Language: pt_BR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: ../../tutorial/datastructures.rst:5
msgid "Data Structures"
msgstr "Estrutura de Dados"
#: ../../tutorial/datastructures.rst:7
msgid ""
"This chapter describes some things you've learned about already in more "
"detail, and adds some new things as well."
msgstr ""
"Esse capítulo descreve algumas coisas que você já aprendeu em detalhes e "
"adiciona algumas coisas novas também."
#: ../../tutorial/datastructures.rst:14
msgid "More on Lists"
msgstr "Mais sobre Listas"
#: ../../tutorial/datastructures.rst:16
msgid ""
"The list data type has some more methods. Here are all of the methods of "
"list objects:"
msgstr ""
"O tipo de dado lista tem ainda mais métodos. Aqui estão apresentados todos "
"os métodos de objetos do tipo lista:"
#: ../../tutorial/datastructures.rst:23
msgid ""
"Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``."
msgstr " Adiciona um item ao fim da lista; equivale a ``a[len(a):] = [x]``."
#: ../../tutorial/datastructures.rst:29
msgid ""
"Extend the list by appending all the items in the given list; equivalent to "
"``a[len(a):] = L``."
msgstr ""
" Prolonga a lista, adicionando no fim todos os elementos da lista ``L``\n"
" passada como argumento; equivalente a ``a[len(a):] = L``."
#: ../../tutorial/datastructures.rst:36
msgid ""
"Insert an item at a given position. The first argument is the index of the "
"element before which to insert, so ``a.insert(0, x)`` inserts at the front "
"of the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``."
msgstr ""
"Insere um item em uma dada posição. O primeiro argumento é o índice do "
"elemento anterior ao qual você deseja inserir, então ``a.insert(0, x)`` "
"insere um elemento na frente da lista e ``a.insert(len(a), x)`` é "
"equivalente a ``a.append(x)``."
#: ../../tutorial/datastructures.rst:44
msgid ""
"Remove the first item from the list whose value is *x*. It is an error if "
"there is no such item."
msgstr ""
"Remove o primeiro item encontrado na lista cujo valor é igual a *x*. Se não "
"existir valor igual, uma exceção ``ValueError`` é levantada."
#: ../../tutorial/datastructures.rst:51
msgid ""
"Remove the item at the given position in the list, and return it. If no "
"index is specified, ``a.pop()`` removes and returns the last item in the "
"list. (The square brackets around the *i* in the method signature denote "
"that the parameter is optional, not that you should type square brackets at "
"that position. You will see this notation frequently in the Python Library "
"Reference.)"
msgstr ""
"Remove um item em uma dada posição na lista e o retorna. Se nenhum índice é "
"especificado, ``a.pop()`` remove e retorna o último item da lista. (O "
"colchetes na frente do *i* na demonstração do método indica que o parâmetro "
"é opcional, e não que é necessário escrever estes colchetes ao chamar o "
"método. Você verá este tipo de notação frequentemente na Biblioteca de "
"Referência Python.)"
#: ../../tutorial/datastructures.rst:61
msgid ""
"Return the index in the list of the first item whose value is *x*. It is an "
"error if there is no such item."
msgstr ""
" Devolve o índice do primeiro item cujo valor é igual a *x*, gerando "
"``ValueError`` se este valor não existe"
#: ../../tutorial/datastructures.rst:68
msgid "Return the number of times *x* appears in the list."
msgstr "Retorna o número de vezes em que *x* aparece na lista."
#: ../../tutorial/datastructures.rst:74
msgid ""
"Sort the items of the list in place (the arguments can be used for sort "
"customization, see :func:`sorted` for their explanation)."
msgstr ""
"Ordena os itens da lista em questão (os argumentos podem ser usados para "
"customizar a ordenação, veja a função :func:`sorted` para maiores "
"explicações)."
#: ../../tutorial/datastructures.rst:81
msgid "Reverse the elements of the list, in place."
msgstr ""
" Inverte a ordem dos elementos na lista *in place* (sem gerar uma nova "
"lista)."
#: ../../tutorial/datastructures.rst:83
msgid "An example that uses most of the list methods::"
msgstr "Um exemplo que usa a maior parte dos métodos das listas::"
#: ../../tutorial/datastructures.rst:108
msgid ""
"You might have noticed that methods like ``insert``, ``remove`` or ``sort`` "
"that only modify the list have no return value printed -- they return the "
"default ``None``. This is a design principle for all mutable data "
"structures in Python."
msgstr ""
"Talvez tenhas observado que métodos como ``insert``, ``remove`` ou ``sort`` que modificam apenas a lista não têm nenhum valor de retorno impresso (que pode ser enviado para a saída padrão) - eles retornam simplesmente o valor ``None`` padrão. Isso foi definido como um princípio de design e utilizado em todas as estruturas de dados mutáveis em Python.\n"
"(N.d.T. Note que os métodos que alteram a lista, inclusive ``sort`` e\n"
"``reverse``, devolvem ``None`` para lembrar o programador de que modificam a\n"
"própria lista, e não criam uma nova. O único método que altera a lista e\n"
"devolve um valor é o ``pop``)"
#: ../../tutorial/datastructures.rst:117
msgid "Using Lists as Stacks"
msgstr "Usando listas como pilhas"
#: ../../tutorial/datastructures.rst:122
msgid ""
"The list methods make it very easy to use a list as a stack, where the last "
"element added is the first element retrieved (\"last-in, first-out\"). To "
"add an item to the top of the stack, use :meth:`append`. To retrieve an "
"item from the top of the stack, use :meth:`pop` without an explicit index. "
"For example::"
msgstr ""
"Os métodos de lista tornam muito fácil utilizar listas como pilhas, onde o "
"item adicionado por último é o primeiro a ser recuperado (política “último a"
" entrar, primeiro a sair”). Para adicionar um item ao topo da pilha, use "
":meth:`append`. Para recuperar um item do topo da pilha use :meth:`pop` sem "
"nenhum índice. Por exemplo::"
#: ../../tutorial/datastructures.rst:147
msgid "Using Lists as Queues"
msgstr "Usando listas como filas"
#: ../../tutorial/datastructures.rst:151
msgid ""
"It is also possible to use a list as a queue, where the first element added "
"is the first element retrieved (\"first-in, first-out\"); however, lists are"
" not efficient for this purpose. While appends and pops from the end of "
"list are fast, doing inserts or pops from the beginning of a list is slow "
"(because all of the other elements have to be shifted by one)."
msgstr ""
"Você também pode usar uma lista como uma fila, onde o primeiro item "
"adicionado é o primeiro a ser recuperado (política “primeiro a entrar, "
"primeiro a sair”); porém, listas não são eficientes para esta finalidade. "
"Embora *appends* e *pops* no final da lista sejam rápidos, fazer *inserts* "
"ou *pops* no início da lista é lento (porque todos os demais elementos têm "
"que ser deslocados)."
#: ../../tutorial/datastructures.rst:157
msgid ""
"To implement a queue, use :class:`collections.deque` which was designed to "
"have fast appends and pops from both ends. For example::"
msgstr ""
"Para implementar uma fila, use a classe :class:`collections.deque` que foi\n"
"projetada para permitir *appends* e *pops* eficientes nas duas extremidades.\n"
"Por exemplo::"
#: ../../tutorial/datastructures.rst:175
msgid "Functional Programming Tools"
msgstr "Ferramentas de programação funcional"
#: ../../tutorial/datastructures.rst:177
msgid ""
"There are three built-in functions that are very useful when used with "
"lists: :func:`filter`, :func:`map`, and :func:`reduce`."
msgstr ""
"Existem três funções embutidas que são muito úteis para processar listas: "
":func:`filter`, :func:`map`, e :func:`reduce`."
#: ../../tutorial/datastructures.rst:180
msgid ""
"``filter(function, sequence)`` returns a sequence consisting of those items "
"from the sequence for which ``function(item)`` is true. If *sequence* is a "
":class:`str`, :class:`unicode` or :class:`tuple`, the result will be of the "
"same type; otherwise, it is always a :class:`list`. For example, to compute"
" a sequence of numbers divisible by 3 or 5::"
msgstr ""
"``filter(funcao, sequencia)`` devolve uma nova sequência formada pelos itens do\n"
"segundo argumento para os quais ``funcao(item)`` é verdadeiro. Se a sequencia\n"
"de entrada for string ou tupla, a saída será do mesmo tipo; caso contrário, o\n"
"resultado será sempre uma lista. Por exemplo, para computar uma sequência de\n"
"números não divisíveis por 2 ou 3::"
#: ../../tutorial/datastructures.rst:191
msgid ""
"``map(function, sequence)`` calls ``function(item)`` for each of the "
"sequence's items and returns a list of the return values. For example, to "
"compute some cubes::"
msgstr ""
"``map(funcao, sequencia)`` aplica ``funcao(item)`` a cada item da sequência e\n"
"devolve uma lista formada pelo resultado de cada aplicação. Por exemplo, para\n"
"computar cubos::"
#: ../../tutorial/datastructures.rst:200
msgid ""
"More than one sequence may be passed; the function must then have as many "
"arguments as there are sequences and is called with the corresponding item "
"from each sequence (or ``None`` if some sequence is shorter than another). "
"For example::"
msgstr ""
"Mais de uma sequência pode ser passada; a função a ser aplicada deve aceitar\n"
"tantos argumentos quantas sequências forem passadas, e é invocada com o item\n"
"correspondente de cada sequência (ou ``None``, se alguma sequência for menor\n"
"que outra). Por exemplo::"
#: ../../tutorial/datastructures.rst:211
msgid ""
"``reduce(function, sequence)`` returns a single value constructed by calling"
" the binary function *function* on the first two items of the sequence, then"
" on the result and the next item, and so on. For example, to compute the "
"sum of the numbers 1 through 10::"
msgstr ""
"A função ``reduce(funcao, sequencia)`` devolve um único valor construído a\n"
"partir da sucessiva aplicação da função binária (N.d.T. que recebe dois\n"
"argumentos) a todos os elementos da lista fornecida, começando pelos dois\n"
"primeiros itens, depois aplicando a função ao primeiro resultado obtido e ao\n"
"próximo item, e assim por diante. Por exemplo, para computar a soma dos\n"
"inteiros de 1 a 10::"
#: ../../tutorial/datastructures.rst:221
msgid ""
"If there's only one item in the sequence, its value is returned; if the "
"sequence is empty, an exception is raised."
msgstr ""
"Se houver um único elemento na sequência fornecida, seu valor será devolvido.\n"
"Se a sequência estiver vazia, uma exceção será levantada."
#: ../../tutorial/datastructures.rst:224
msgid ""
"A third argument can be passed to indicate the starting value. In this case"
" the starting value is returned for an empty sequence, and the function is "
"first applied to the starting value and the first sequence item, then to the"
" result and the next item, and so on. For example, ::"
msgstr ""
"Um terceiro argumento pode ser passado para definir o valor inicial. Neste\n"
"caso, redução de uma sequência vazia devolve o valor inicial. Do contrário, a\n"
"redução se inicia aplicando a função ao valor inicial e ao primeiro elemento\n"
"da sequência, e continuando a partir daí. ::"
#: ../../tutorial/datastructures.rst:238
msgid ""
"Don't use this example's definition of :func:`sum`: since summing numbers is"
" such a common need, a built-in function ``sum(sequence)`` is already "
"provided, and works exactly like this."
msgstr ""
"Não use a função ``somatória`` deste exemplo; somar sequências de números é uma\n"
"necessidade comum, e para isso Python tem a função embutida :func:`sum`, que\n"
"faz exatamente isto, e também aceita um valor inicial (opcional)."
#: ../../tutorial/datastructures.rst:245
msgid "List Comprehensions"
msgstr "Compreensões de lista"
#: ../../tutorial/datastructures.rst:247
msgid ""
"List comprehensions provide a concise way to create lists. Common "
"applications are to make new lists where each element is the result of some "
"operations applied to each member of another sequence or iterable, or to "
"create a subsequence of those elements that satisfy a certain condition."
msgstr ""
"Uma *list comprehension* é uma maneira concisa de construir uma lista "
"preenchida. (N.d.T. literalmente, *abrangência de lista* mas no Brasil o "
"termo em inglês é muito usado; também se usa a abreviação *listcomp*)"
#: ../../tutorial/datastructures.rst:252
msgid "For example, assume we want to create a list of squares, like::"
msgstr ""
"Por exemplo, suponha que queremos criar uma lista de quadrados, assim::"
#: ../../tutorial/datastructures.rst:261
msgid "We can obtain the same result with::"
msgstr "Podemos obter o mesmo resultado desta forma::"
#: ../../tutorial/datastructures.rst:265
msgid ""
"This is also equivalent to ``squares = map(lambda x: x**2, range(10))``, but"
" it's more concise and readable."
msgstr ""
"Isso equivale a ``quadrados = map(lambda x: x**2, range(10))``, mas é mais\n"
"conciso e legível."
#: ../../tutorial/datastructures.rst:268
msgid ""
"A list comprehension consists of brackets containing an expression followed "
"by a :keyword:`for` clause, then zero or more :keyword:`for` or "
":keyword:`if` clauses. The result will be a new list resulting from "
"evaluating the expression in the context of the :keyword:`for` and "
":keyword:`if` clauses which follow it. For example, this listcomp combines "
"the elements of two lists if they are not equal::"
msgstr ""
"Uma abrangência de lista é formada por um par de colchetes contendo uma\n"
"expressão seguida de uma cláusula :keyword:`for`, e então zero ou mais\n"
"cláusulas :keyword:`for` ou :keyword:`if`. O resultado será uma lista\n"
"resultante da avaliação da expressão no contexto das cláusulas :keyword:`for`\n"
"e :keyword:`if`."
#: ../../tutorial/datastructures.rst:278
msgid "and it's equivalent to:"
msgstr "e isso é equivalente a:"
#: ../../tutorial/datastructures.rst:289
msgid ""
"Note how the order of the :keyword:`for` and :keyword:`if` statements is the"
" same in both these snippets."
msgstr ""
"Uma abrangência de lista é formada por um par de colchetes contendo uma\n"
"expressão seguida de uma cláusula :keyword:`for`, e então zero ou mais\n"
"cláusulas :keyword:`for` ou :keyword:`if`. O resultado será uma lista\n"
"resultante da avaliação da expressão no contexto das cláusulas :keyword:`for`\n"
"e :keyword:`if`."
#: ../../tutorial/datastructures.rst:292
msgid ""
"If the expression is a tuple (e.g. the ``(x, y)`` in the previous example), "
"it must be parenthesized. ::"
msgstr ""
"Se a expressão é uma tupla, ela deve ser inserida entre parênteses (ex., "
"``(x, y)`` no exemplo anterior). ::"
#: ../../tutorial/datastructures.rst:323
msgid ""
"List comprehensions can contain complex expressions and nested functions::"
msgstr ""
"List comprehensions podem conter expressões complexas e funções aninhadas::"
#: ../../tutorial/datastructures.rst:331
msgid "Nested List Comprehensions"
msgstr "List Comprehensions aninhadas"
#: ../../tutorial/datastructures.rst:333
msgid ""
"The initial expression in a list comprehension can be any arbitrary "
"expression, including another list comprehension."
msgstr ""
"A expressão inicial em uma list comprehension pode ser qualquer expressão "
"arbitrária, incluindo outra list comprehension."
#: ../../tutorial/datastructures.rst:336
msgid ""
"Consider the following example of a 3x4 matrix implemented as a list of 3 "
"lists of length 4::"
msgstr ""
"Considere o exemplo seguinte de uma matriz 3x4 implementada com uma lista de"
" 3 listas de tamanho 4::"
#: ../../tutorial/datastructures.rst:345
msgid "The following list comprehension will transpose rows and columns::"
msgstr "A abrangência de listas abaixo transpõe as linhas e colunas::"
#: ../../tutorial/datastructures.rst:350
msgid ""
"As we saw in the previous section, the nested listcomp is evaluated in the "
"context of the :keyword:`for` that follows it, so this example is equivalent"
" to::"
msgstr ""
"Como vimos na seção anterior, a listcomp aninhada é computada no contexto\n"
"da cláusula :keyword:`for` seguinte, portanto o exemplo acima equivale a::"
#: ../../tutorial/datastructures.rst:361
msgid "which, in turn, is the same as::"
msgstr "e isso, por sua vez, faz o mesmo que isto::"
#: ../../tutorial/datastructures.rst:375
msgid ""
"In the real world, you should prefer built-in functions to complex flow "
"statements. The :func:`zip` function would do a great job for this use "
"case::"
msgstr ""
"Na prática, você deve dar preferência a funções embutidas em vez de expressões\n"
"complexas. A função :func:`zip` resolve muito bem este caso de uso::"
#: ../../tutorial/datastructures.rst:381
msgid ""
"See :ref:`tut-unpacking-arguments` for details on the asterisk in this line."
msgstr ""
"Veja :ref:`tut-unpacking-arguments` para entender o uso do asterisco neste "
"exemplo."
#: ../../tutorial/datastructures.rst:386
msgid "The :keyword:`del` statement"
msgstr "O comando :keyword:`del`"
#: ../../tutorial/datastructures.rst:388
msgid ""
"There is a way to remove an item from a list given its index instead of its "
"value: the :keyword:`del` statement. This differs from the :meth:`pop` "
"method which returns a value. The :keyword:`del` statement can also be used"
" to remove slices from a list or clear the entire list (which we did earlier"
" by assignment of an empty list to the slice). For example::"
msgstr ""
"Existe uma maneira de remover um item de uma lista conhecendo seu índice, ao\n"
"invés de seu valor: o comando :keyword:`del`. Ele difere do método\n"
":meth:`list.pop`, que devolve o item removido. O comando :keyword:`del` também\n"
"pode ser utilizado para remover fatias (slices) da lista, ou mesmo limpar a\n"
"lista toda (que fizemos antes atribuindo uma lista vazia à fatia ``a[:]``). Por\n"
"exemplo::"
#: ../../tutorial/datastructures.rst:405
msgid ":keyword:`del` can also be used to delete entire variables::"
msgstr ""
":keyword:`del` também pode ser usado para remover totalmente uma variável::"
#: ../../tutorial/datastructures.rst:409
msgid ""
"Referencing the name ``a`` hereafter is an error (at least until another "
"value is assigned to it). We'll find other uses for :keyword:`del` later."
msgstr ""
"Referenciar a variável ``a`` depois de sua remoção constitui erro (pelo menos\n"
"até que seja feita uma nova atribuição para ela). Encontraremos outros\n"
"usos para o comando :keyword:`del` mais tarde."
#: ../../tutorial/datastructures.rst:416
msgid "Tuples and Sequences"
msgstr "Tuplas e Sequências"
#: ../../tutorial/datastructures.rst:418
msgid ""
"We saw that lists and strings have many common properties, such as indexing "
"and slicing operations. They are two examples of *sequence* data types (see"
" :ref:`typesseq`). Since Python is an evolving language, other sequence "
"data types may be added. There is also another standard sequence data type:"
" the *tuple*."
msgstr ""
"Vimos que listas e strings têm muitas propriedades em comum, como indexação e\n"
"operações de fatiamento (*slicing*). Elas são dois exemplos de *sequências*\n"
"(veja :ref:`typesseq`). Como Python é uma linguagem em evolução, outros tipos\n"
"de sequências podem ser adicionados. Existe ainda um outro tipo de sequência\n"
"padrão na linguagem: a tupla (*tuple*)."
#: ../../tutorial/datastructures.rst:424
msgid ""
"A tuple consists of a number of values separated by commas, for instance::"
msgstr ""
"Uma tupla consiste em uma sequência de valores separados por vírgulas::"
#: ../../tutorial/datastructures.rst:446
msgid ""
"As you see, on output tuples are always enclosed in parentheses, so that "
"nested tuples are interpreted correctly; they may be input with or without "
"surrounding parentheses, although often parentheses are necessary anyway (if"
" the tuple is part of a larger expression). It is not possible to assign to"
" the individual items of a tuple, however it is possible to create tuples "
"which contain mutable objects, such as lists."
msgstr ""
"Como você pode ver no trecho acima, na saída do console as tuplas são sempre\n"
"envolvidas por parênteses, assim tuplas aninhadas podem ser lidas\n"
"corretamente. Na criação, tuplas podem ser envolvidas ou não por parênteses,\n"
"desde que o contexto não exija os parênteses (como no caso da tupla dentro\n"
"a uma expressão maior)."
#: ../../tutorial/datastructures.rst:453
msgid ""
"Though tuples may seem similar to lists, they are often used in different "
"situations and for different purposes. Tuples are :term:`immutable`, and "
"usually contain a heterogeneous sequence of elements that are accessed via "
"unpacking (see later in this section) or indexing (or even by attribute in "
"the case of :func:`namedtuples <collections.namedtuple>`). Lists are "
":term:`mutable`, and their elements are usually homogeneous and are accessed"
" by iterating over the list."
msgstr ""
"Tuplas podem ser usadas de diversas formas: pares ordenados ``(x, y)``,\n"
"registros de funcionário extraídos uma base de dados, etc. Tuplas, assim como\n"
"strings, são imutáveis: não é possível atribuir valores a itens individuais de\n"
"uma tupla (você pode simular o mesmo efeito através de operações de fatiamento\n"
"e concatenação; N.d.T. mas neste caso nunca estará modificando tuplas, apenas\n"
"criando novas). Também é possível criar tuplas contendo objetos mutáveis,\n"
"como listas."
#: ../../tutorial/datastructures.rst:461
msgid ""
"A special problem is the construction of tuples containing 0 or 1 items: the"
" syntax has some extra quirks to accommodate these. Empty tuples are "
"constructed by an empty pair of parentheses; a tuple with one item is "
"constructed by following a value with a comma (it is not sufficient to "
"enclose a single value in parentheses). Ugly, but effective. For example::"
msgstr ""
"Um problema especial é a criação de tuplas contendo 0 ou 1 itens: a sintaxe\n"
"usa certos truques para acomodar estes casos. Tuplas vazias são construídas\n"
"por uma par de parênteses vazios; uma tupla unitária é construída por um\n"
"único valor e uma vírgula entre parênteses (não basta colocar um único valor\n"
"entre parênteses). Feio, mas funciona::"
#: ../../tutorial/datastructures.rst:476
msgid ""
"The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple "
"packing*: the values ``12345``, ``54321`` and ``'hello!'`` are packed "
"together in a tuple. The reverse operation is also possible::"
msgstr ""
"O comando ``t = 12345, 54321, 'hello!'`` é um exemplo de *empacotamento de\n"
"tupla* (*tuple packing*): os valores ``12345``, ``54321`` e ``'bom dia!'`` são\n"
"empacotados juntos em uma tupla. A operação inversa também é possível::"
#: ../../tutorial/datastructures.rst:482
msgid ""
"This is called, appropriately enough, *sequence unpacking* and works for any"
" sequence on the right-hand side. Sequence unpacking requires the list of "
"variables on the left to have the same number of elements as the length of "
"the sequence. Note that multiple assignment is really just a combination of"
" tuple packing and sequence unpacking."
msgstr ""
"Isto é chamado de desempacotamento de sequência (*sequence unpacking*), funciona\n"
"para qualquer tipo de sequência do lado direito. Para funcionar, é necessário\n"
"que a lista de variáveis do lado esquerdo tenha o mesmo comprimento da\n"
"sequência à direita. Sendo assim, a atribuição múltipla é um caso de\n"
"empacotamento de tupla e desempacotamento de sequência::"
#: ../../tutorial/datastructures.rst:492
msgid "Sets"
msgstr "Sets (conjuntos)"
#: ../../tutorial/datastructures.rst:494
msgid ""
"Python also includes a data type for *sets*. A set is an unordered "
"collection with no duplicate elements. Basic uses include membership "
"testing and eliminating duplicate entries. Set objects also support "
"mathematical operations like union, intersection, difference, and symmetric "
"difference."
msgstr ""
"Python também inclui um tipo de dados para conjuntos, chamado ``set``. Um\n"
"conjunto é uma coleção desordenada de elementos, sem elementos repetidos. Usos\n"
"comuns para sets incluem a verificação eficiente da existência de objetos e a\n"
"eliminação de itens duplicados. Conjuntos também suportam operações\n"
"matemáticas como união, interseção, diferença e diferença simétrica."
#: ../../tutorial/datastructures.rst:499
msgid ""
"Curly braces or the :func:`set` function can be used to create sets. Note: "
"to create an empty set you have to use ``set()``, not ``{}``; the latter "
"creates an empty dictionary, a data structure that we discuss in the next "
"section."
msgstr ""
"Chaves ou a função :func:`set` podem ser usados para criar conjuntos. Note: "
"para criar um conjunto vazio você precisa usar ``set()``, não ``{}``; este "
"último cria um dicionário vazio, uma estrutura de dados que discutiremos na "
"próxima seção."
#: ../../tutorial/datastructures.rst:503
msgid "Here is a brief demonstration::"
msgstr "Uma pequena demonstração:"
#: ../../tutorial/datastructures.rst:529
msgid ""
"Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions "
"are also supported::"
msgstr ""
"Da mesma forma que :ref:`list comprehensions <tut-listcomps>`, set "
"comprehensions também são suportadas::"
#: ../../tutorial/datastructures.rst:540
msgid "Dictionaries"
msgstr "Dicionários"
#: ../../tutorial/datastructures.rst:542
msgid ""
"Another useful data type built into Python is the *dictionary* (see "
":ref:`typesmapping`). Dictionaries are sometimes found in other languages as"
" \"associative memories\" or \"associative arrays\". Unlike sequences, "
"which are indexed by a range of numbers, dictionaries are indexed by *keys*,"
" which can be any immutable type; strings and numbers can always be keys. "
"Tuples can be used as keys if they contain only strings, numbers, or tuples;"
" if a tuple contains any mutable object either directly or indirectly, it "
"cannot be used as a key. You can't use lists as keys, since lists can be "
"modified in place using index assignments, slice assignments, or methods "
"like :meth:`append` and :meth:`extend`."
msgstr ""
"Outra estrutura de dados muito útil embutida em Python é o *dicionário*, cujo\n"
"tipo é ``dict`` (ver :ref:`typesmapping`). Dicionários são também chamados de\n"
"“memória associativa” ou “vetor associativo” em outras linguagens. Diferente\n"
"de sequências que são indexadas por inteiros, dicionários são indexados por\n"
"chaves (*keys*), que podem ser de qualquer tipo imutável (como strings e\n"
"inteiros). Tuplas também podem ser chaves se contiverem apenas strings,\n"
"inteiros ou outras tuplas. Se a tupla contiver, direta ou indiretamente,\n"
"qualquer valor mutável, não poderá ser chave. Listas não podem ser usadas como\n"
"chaves porque podem ser modificadas *in place* pela atribuição em índices ou\n"
"fatias, e por métodos como :meth:`append` e :meth:`extend`."
#: ../../tutorial/datastructures.rst:553
msgid ""
"It is best to think of a dictionary as an unordered set of *key: value* "
"pairs, with the requirement that the keys are unique (within one "
"dictionary). A pair of braces creates an empty dictionary: ``{}``. Placing a"
" comma-separated list of key:value pairs within the braces adds initial "
"key:value pairs to the dictionary; this is also the way dictionaries are "
"written on output."
msgstr ""
"Um bom modelo mental é imaginar um dicionário como um conjunto não ordenado de\n"
"pares chave-valor, onde as chaves são únicas em uma dada instância do\n"
"dicionário. Dicionários são delimitados por chaves: ``{}``, e contém uma lista\n"
"de pares *chave:valor* separada por vírgulas. Dessa forma também será exibido\n"
"o conteúdo de um dicionário no console do Python. O dicionário vazio é ``{}``."
#: ../../tutorial/datastructures.rst:559
msgid ""
"The main operations on a dictionary are storing a value with some key and "
"extracting the value given the key. It is also possible to delete a "
"key:value pair with ``del``. If you store using a key that is already in "
"use, the old value associated with that key is forgotten. It is an error to"
" extract a value using a non-existent key."
msgstr ""
"As principais operações em um dicionário são armazenar e recuperar valores a\n"
"partir de chaves. Também é possível remover um par *chave:valor* com o comando\n"
"``del``. Se você armazenar um valor utilizando uma chave já presente, o antigo\n"
"valor será substituído pelo novo. Se tentar recuperar um valor usando uma chave\n"
"inexistente, será gerado um erro."
#: ../../tutorial/datastructures.rst:565
msgid ""
"The :meth:`keys` method of a dictionary object returns a list of all the "
"keys used in the dictionary, in arbitrary order (if you want it sorted, just"
" apply the :func:`sorted` function to it). To check whether a single key is"
" in the dictionary, use the :keyword:`in` keyword."
msgstr ""
"O método :meth:`keys` do dicionário devolve a lista de todas as chaves\n"
"presentes no dicionário, em ordem arbitrária (se desejar ordená-las basta\n"
"aplicar o a função :func:`sorted` à lista devolvida). Para verificar a\n"
"existência de uma chave, use o operador :keyword:`in`."
#: ../../tutorial/datastructures.rst:570
msgid "Here is a small example using a dictionary::"
msgstr "A seguir, um exemplo de uso do dicionário:"
#: ../../tutorial/datastructures.rst:587
msgid ""
"The :func:`dict` constructor builds dictionaries directly from sequences of "
"key-value pairs::"
msgstr ""
"O construtor :func:`dict` produz dicionários diretamente a partir de uma "
"lista de chaves-valores, armazenadas como duplas (tuplas de 2 elementos). "
"Quando os pares formam um padrão, uma list comprehensions pode especificar a"
" lista de chaves-valores de forma mais compacta. ::"
#: ../../tutorial/datastructures.rst:593
msgid ""
"In addition, dict comprehensions can be used to create dictionaries from "
"arbitrary key and value expressions::"
msgstr ""
"Além disso, os dict comprehensions podem ser usadas para criar dicionários a"
" partir de expressões arbitrárias de chave e valor::"
#: ../../tutorial/datastructures.rst:599
msgid ""
"When the keys are simple strings, it is sometimes easier to specify pairs "
"using keyword arguments::"
msgstr ""
"Quando chaves são strings simples, é mais fácil especificar os pares usando\n"
"argumentos nomeados no construtor:"
#: ../../tutorial/datastructures.rst:609
msgid "Looping Techniques"
msgstr "Técnicas de Iteração"
#: ../../tutorial/datastructures.rst:611
msgid ""
"When looping through a sequence, the position index and corresponding value "
"can be retrieved at the same time using the :func:`enumerate` function. ::"
msgstr ""
"Ao percorrer um dicionário em um laço, a variável de iteração receberá uma "
"chave de cada vez::"
#: ../../tutorial/datastructures.rst:621
msgid ""
"To loop over two or more sequences at the same time, the entries can be "
"paired with the :func:`zip` function. ::"
msgstr ""
"Para percorrer duas ou mais sequências simultaneamente com o laço, os itens\n"
"podem ser agrupados com a função :func:`zip`. ::"
#: ../../tutorial/datastructures.rst:633
msgid ""
"To loop over a sequence in reverse, first specify the sequence in a forward "
"direction and then call the :func:`reversed` function. ::"
msgstr ""
"Para percorrer uma sequência em ordem inversa, chame a função "
":func:`reversed` com a sequência na ordem original. ::"
#: ../../tutorial/datastructures.rst:645
msgid ""
"To loop over a sequence in sorted order, use the :func:`sorted` function "
"which returns a new sorted list while leaving the source unaltered. ::"
msgstr ""
"Para percorrer uma sequência de maneira ordenada, use a função :func:`sorted`,\n"
"que retorna uma lista ordenada com os itens, mantendo a sequência original\n"
"inalterada. ::"
#: ../../tutorial/datastructures.rst:657
msgid ""
"When looping through dictionaries, the key and corresponding value can be "
"retrieved at the same time using the :meth:`iteritems` method. ::"
msgstr ""
#: ../../tutorial/datastructures.rst:667
msgid ""
"It is sometimes tempting to change a list while you are looping over it; "
"however, it is often simpler and safer to create a new list instead. ::"
msgstr ""
"Às vezes é tentador alterar uma lista enquanto você itera sobre ela; porém, "
"costuma ser mais simples e seguro criar uma nova lista. ::"
#: ../../tutorial/datastructures.rst:684
msgid "More on Conditions"
msgstr "Mais sobre condições"
#: ../../tutorial/datastructures.rst:686
msgid ""
"The conditions used in ``while`` and ``if`` statements can contain any "
"operators, not just comparisons."
msgstr ""
"As condições de controle usadas em ``while`` e ``if`` podem conter quaisquer"
" operadores, não apenas comparações."
#: ../../tutorial/datastructures.rst:689
msgid ""
"The comparison operators ``in`` and ``not in`` check whether a value occurs "
"(does not occur) in a sequence. The operators ``is`` and ``is not`` compare"
" whether two objects are really the same object; this only matters for "
"mutable objects like lists. All comparison operators have the same "
"priority, which is lower than that of all numerical operators."
msgstr ""
"Os operadores de comparação ``in`` e ``not in`` verificam se um valor ocorre\n"
"(ou não ocorre) em uma dada sequência. Os operadores ``is`` e ``is not``\n"
"comparam se dois objetos são na verdade o mesmo objeto; isto só é relevante no\n"
"contexto de objetos mutáveis, como listas. Todos os operadores de comparação\n"
"possuem a mesma precedência, que é menor do que a prioridade de todos os\n"
"operadores numéricos."
#: ../../tutorial/datastructures.rst:695
msgid ""
"Comparisons can be chained. For example, ``a < b == c`` tests whether ``a``"
" is less than ``b`` and moreover ``b`` equals ``c``."
msgstr ""
"Comparações podem ser encadeadas: Por exemplo ``a < b == c`` testa se ``a`` é menor\n"
"que ``b`` e também se ``b`` é igual a ``c``."
#: ../../tutorial/datastructures.rst:698
msgid ""
"Comparisons may be combined using the Boolean operators ``and`` and ``or``, "
"and the outcome of a comparison (or of any other Boolean expression) may be "
"negated with ``not``. These have lower priorities than comparison "
"operators; between them, ``not`` has the highest priority and ``or`` the "
"lowest, so that ``A and not B or C`` is equivalent to ``(A and (not B)) or "
"C``. As always, parentheses can be used to express the desired composition."
msgstr ""
"Comparações podem ser combinadas através de operadores booleanos ``and`` e\n"
"``or``, e o resultado de uma comparação (ou de qualquer outra expressão), pode\n"
"ter seu valor booleano negado através de ``not``. Estes possuem menor\n"
"prioridade que os demais operadores de comparação. Entre eles, ``not`` é o de\n"
"maior prioridade e ``or`` o de menor. Dessa forma, a condição ``A and not B or\n"
"C`` é equivalente a ``(A and (not B)) or C``. Naturalmente, parênteses podem\n"
"ser usados para expressar o agrupamento desejado."
#: ../../tutorial/datastructures.rst:705
msgid ""
"The Boolean operators ``and`` and ``or`` are so-called *short-circuit* "
"operators: their arguments are evaluated from left to right, and evaluation "
"stops as soon as the outcome is determined. For example, if ``A`` and ``C``"
" are true but ``B`` is false, ``A and B and C`` does not evaluate the "
"expression ``C``. When used as a general value and not as a Boolean, the "
"return value of a short-circuit operator is the last evaluated argument."
msgstr ""
"Os operadores booleanos ``and`` e ``or`` são operadores *short-circuit*: seus\n"
"argumentos são avaliados da esquerda para a direita, e a avaliação para quando\n"
"o resultado é determinado. Por exemplo, se ``A`` e ``C`` são expressões\n"
"verdadeiras, mas ``B`` é falsa, então ``A and B and C`` não chega a avaliar a\n"
"expressão ``C``. Em geral, quando usado sobre valores genéricos e não\n"
"como booleanos, o valor do resultado de um operador atalho é o último valor\n"
"avaliado na expressão."
#: ../../tutorial/datastructures.rst:712
msgid ""
"It is possible to assign the result of a comparison or other Boolean "
"expression to a variable. For example, ::"
msgstr ""
"É possível atribuir o resultado de uma comparação ou outra expressão booleana\n"
"para uma variável. Por exemplo::"
#: ../../tutorial/datastructures.rst:720
msgid ""
"Note that in Python, unlike C, assignment cannot occur inside expressions. C"
" programmers may grumble about this, but it avoids a common class of "
"problems encountered in C programs: typing ``=`` in an expression when "
"``==`` was intended."
msgstr ""
"Observe que em Python, diferente de C, atribuição não pode ocorrer dentro\n"
"de uma expressão. Programadores C podem resmungar, mas isso evita toda uma\n"
"classe de problemas frequentemente encontrados em programas C: digitar ``=``\n"
"numa expressão quando a intenção era ``==``."
#: ../../tutorial/datastructures.rst:729
msgid "Comparing Sequences and Other Types"
msgstr "Comparando sequências e outros tipos"
#: ../../tutorial/datastructures.rst:731
msgid ""
"Sequence objects may be compared to other objects with the same sequence "
"type. The comparison uses *lexicographical* ordering: first the first two "
"items are compared, and if they differ this determines the outcome of the "
"comparison; if they are equal, the next two items are compared, and so on, "
"until either sequence is exhausted. If two items to be compared are "
"themselves sequences of the same type, the lexicographical comparison is "
"carried out recursively. If all items of two sequences compare equal, the "
"sequences are considered equal. If one sequence is an initial sub-sequence "
"of the other, the shorter sequence is the smaller (lesser) one. "
"Lexicographical ordering for strings uses the ASCII ordering for individual "
"characters. Some examples of comparisons between sequences of the same "
"type::"
msgstr ""
"Objetos sequência podem ser comparados com outros objetos sequência, desde que\n"
"o tipo das sequências seja o mesmo. A comparação utiliza a ordem\n"
"*lexicográfica*: primeiramente os dois primeiros itens são comparados, e se\n"
"diferirem isto determinará o resultado da comparação, caso contrário os\n"
"próximos dois itens serão comparados, e assim por diante até que se tenha\n"
"exaurido alguma das sequências. Se em uma comparação de itens, os mesmos forem\n"
"também sequências (aninhadas), então é disparada recursivamente outra\n"
"comparação lexicográfica. Se todos os itens da sequência forem iguais, então\n"
"as sequências são ditas iguais. Se uma das sequências é uma subsequência da\n"
"outra, então a subsequência é a menor. A comparação lexicográfica de strings\n"
"utiliza ASCII para definir a ordenação. Alguns exemplos de comparações entre\n"
"sequências do mesmo tipo::"
#: ../../tutorial/datastructures.rst:751
msgid ""
"Note that comparing objects of different types is legal. The outcome is "
"deterministic but arbitrary: the types are ordered by their name. Thus, a "
"list is always smaller than a string, a string is always smaller than a "
"tuple, etc. [#]_ Mixed numeric types are compared according to their numeric"
" value, so 0 equals 0.0, etc."
msgstr ""
"É permitido comparar objetos de diferentes tipos. O resultado é\n"
"determinístico, porém, arbitrário: os tipos são ordenados pelos seus nomes.\n"
"Então, uma ``list`` é sempre menor do que uma ``str``, uma ``str`` é sempre\n"
"menor do que uma ``tuple``, etc. [#]_ Tipos numéricos misturados são\n"
"comparados de acordo com seus valores numéricos, logo 0 é igual a 0.0, etc."
#: ../../tutorial/datastructures.rst:759
msgid "Footnotes"
msgstr "Notas de Rodapé"
#: ../../tutorial/datastructures.rst:760
msgid ""
"The rules for comparing objects of different types should not be relied "
"upon; they may change in a future version of the language."
msgstr ""