# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # python-doc bot, 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.11\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-09-22 20:37+0000\n" "PO-Revision-Date: 2025-09-22 16:51+0000\n" "Last-Translator: python-doc bot, 2025\n" "Language-Team: Portuguese (Brazil) (https://app.transifex.com/python-doc/" "teams/5390/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=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % " "1000000 == 0 ? 1 : 2;\n" #: ../../tutorial/datastructures.rst:5 msgid "Data Structures" msgstr "Estruturas 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:13 msgid "More on Lists" msgstr "Mais sobre listas" #: ../../tutorial/datastructures.rst:15 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:22 msgid "" "Add an item to the end of the list. Equivalent to ``a[len(a):] = [x]``." msgstr "Adiciona um item ao fim da lista. Equivalente a ``a[len(a):] = [x]``." #: ../../tutorial/datastructures.rst:28 msgid "" "Extend the list by appending all the items from the iterable. Equivalent to " "``a[len(a):] = iterable``." msgstr "" "Prolonga a lista, adicionando no fim todos os elementos do argumento " "`iterable` passado como parâmetro. Equivalente a ``a[len(a):] = iterable``." #: ../../tutorial/datastructures.rst:35 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 antes do qual será feita a inserção, assim ``a.insert(0, x)`` " "insere um elemento na frente da lista e ``a.insert(len(a), x)`` e equivale a " "``a.append(x)``." #: ../../tutorial/datastructures.rst:43 msgid "" "Remove the first item from the list whose value is equal to *x*. It raises " "a :exc:`ValueError` 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 :exc:`ValueError` é levantada." #: ../../tutorial/datastructures.rst:50 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. It raises an :exc:`IndexError` if the list is empty or the index is " "outside the list range." msgstr "" "Remove o item na posição fornecida na lista e retorna. Se nenhum índice for " "especificado, ``a.pop()`` remove e retorna o último item da lista. Levanta " "um :exc:`IndexError` se a lista estiver vazia ou o índice estiver fora do " "intervalo da lista." #: ../../tutorial/datastructures.rst:59 msgid "Remove all items from the list. Equivalent to ``del a[:]``." msgstr "Remove todos os itens de uma lista. Equivalente a ``del a[:]``." #: ../../tutorial/datastructures.rst:65 msgid "" "Return zero-based index in the list of the first item whose value is equal " "to *x*. Raises a :exc:`ValueError` if there is no such item." msgstr "" "Devolve o índice base-zero do primeiro item cujo valor é igual a *x*, " "levantando :exc:`ValueError` se este valor não existe." #: ../../tutorial/datastructures.rst:68 msgid "" "The optional arguments *start* and *end* are interpreted as in the slice " "notation and are used to limit the search to a particular subsequence of the " "list. The returned index is computed relative to the beginning of the full " "sequence rather than the *start* argument." msgstr "" "Os argumentos opcionais *start* e *end* são interpretados como nas notações " "de fatiamento e são usados para limitar a busca para uma subsequência " "específica da lista. O índice retornado é calculado relativo ao começo da " "sequência inteira e não referente ao argumento *start*." #: ../../tutorial/datastructures.rst:77 msgid "Return the number of times *x* appears in the list." msgstr "Devolve o número de vezes em que *x* aparece na lista." #: ../../tutorial/datastructures.rst:83 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 na lista (os argumentos podem ser usados para personalizar a " "ordenação, veja a função :func:`sorted` para maiores explicações)." #: ../../tutorial/datastructures.rst:90 msgid "Reverse the elements of the list in place." msgstr "Inverte a ordem dos elementos na lista." #: ../../tutorial/datastructures.rst:96 msgid "Return a shallow copy of the list. Equivalent to ``a[:]``." msgstr "Devolve uma cópia rasa da lista. Equivalente a ``a[:]``." #: ../../tutorial/datastructures.rst:99 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:122 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 "" "Você pode ter percebido que métodos como ``insert``, ``remove`` ou ``sort``, " "que apenas modificam a lista, não têm valor de retorno impresso -- eles " "retornam o ``None`` padrão. [#]_ Isto é um princípio de design para todas as " "estruturas de dados mutáveis em Python." #: ../../tutorial/datastructures.rst:127 msgid "" "Another thing you might notice is that not all data can be sorted or " "compared. For instance, ``[None, 'hello', 10]`` doesn't sort because " "integers can't be compared to strings and *None* can't be compared to other " "types. Also, there are some types that don't have a defined ordering " "relation. For example, ``3+4j < 5+7j`` isn't a valid comparison." msgstr "" "Outra coisa que você deve estar atento é que nem todos os dados podem ser " "ordenados ou comparados. Por exemplo, , ``[None, 'hello', 10]`` não podem " "ser ordenados, pois inteiros não podem ser comparados a strings e *None* não " "pode ser comparado a nenhum outro tipo. Além disso, existem alguns tipos de " "dados que não possuem uma relação de ordem definida. Por exemplo, ``3+4j < " "5+7j`` não é uma comparação válida." #: ../../tutorial/datastructures.rst:138 msgid "Using Lists as Stacks" msgstr "Usando listas como pilhas" #: ../../tutorial/datastructures.rst:143 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:`~list.append`. To retrieve " "an item from the top of the stack, use :meth:`~list.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:`~list.append`. Para recuperar um item do topo da pilha use :meth:" "`~list.pop` sem nenhum índice explícito. Por exemplo::" #: ../../tutorial/datastructures.rst:168 msgid "Using Lists as Queues" msgstr "Usando listas como filas" #: ../../tutorial/datastructures.rst:172 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:178 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 " "projetada para permitir *appends* e *pops* eficientes nas duas extremidades. " "Por exemplo::" #: ../../tutorial/datastructures.rst:196 msgid "List Comprehensions" msgstr "Compreensões de lista" #: ../../tutorial/datastructures.rst:198 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 "" "Compreensões de lista fornece uma maneira concisa de criar uma lista. " "Aplicações comuns são criar novas listas onde cada elemento é o resultado de " "alguma operação aplicada a cada elemento de outra sequência ou iterável, ou " "criar uma subsequência de elementos que satisfaçam uma certa condição. (N.d." "T. o termo original em inglês é *list comprehensions*, muito utilizado no " "Brasil; também se usa a abreviação *listcomp*)." #: ../../tutorial/datastructures.rst:203 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:212 msgid "" "Note that this creates (or overwrites) a variable named ``x`` that still " "exists after the loop completes. We can calculate the list of squares " "without any side effects using::" msgstr "" "Note que isto cria (ou sobrescreve) uma variável chamada ``x`` que ainda " "existe após o término do laço. Podemos calcular a lista dos quadrados sem " "qualquer efeito colateral usando::" #: ../../tutorial/datastructures.rst:218 msgid "or, equivalently::" msgstr "ou, de maneira equivalente::" #: ../../tutorial/datastructures.rst:222 msgid "which is more concise and readable." msgstr "que é mais conciso e legível." #: ../../tutorial/datastructures.rst:224 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 "" "Um compreensão de lista consiste de um par de colchetes contendo uma " "expressão seguida de uma cláusula :keyword:`!for`, e então zero ou mais " "cláusulas :keyword:`!for` ou :keyword:`!if`. O resultado será uma nova lista " "resultante da avaliação da expressão no contexto das cláusulas :keyword:`!" "for` e :keyword:`!if`. Por exemplo, essa compreensão combina os elementos de " "duas listas se eles forem diferentes::" #: ../../tutorial/datastructures.rst:234 msgid "and it's equivalent to::" msgstr "e é equivalente a::" #: ../../tutorial/datastructures.rst:245 msgid "" "Note how the order of the :keyword:`for` and :keyword:`if` statements is the " "same in both these snippets." msgstr "" "Note como a ordem das instruções :keyword:`for` e :keyword:`if` é a mesma em " "ambos os trechos." #: ../../tutorial/datastructures.rst:248 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 (ex., ``(x, y)`` no exemplo anterior), ela deve " "ser inserida entre parênteses. ::" #: ../../tutorial/datastructures.rst:279 msgid "" "List comprehensions can contain complex expressions and nested functions::" msgstr "" "Compreensões de lista podem conter expressões complexas e funções aninhadas::" #: ../../tutorial/datastructures.rst:286 msgid "Nested List Comprehensions" msgstr "Compreensões de lista aninhadas" #: ../../tutorial/datastructures.rst:288 msgid "" "The initial expression in a list comprehension can be any arbitrary " "expression, including another list comprehension." msgstr "" "A expressão inicial em uma compreensão de lista pode ser qualquer expressão " "arbitrária, incluindo outra compreensão de lista." #: ../../tutorial/datastructures.rst:291 msgid "" "Consider the following example of a 3x4 matrix implemented as a list of 3 " "lists of length 4::" msgstr "" "Observe este exemplo de uma matriz 3x4 implementada como uma lista de 3 " "listas de comprimento 4::" #: ../../tutorial/datastructures.rst:300 msgid "The following list comprehension will transpose rows and columns::" msgstr "A compreensão de lista abaixo transpõe as linhas e colunas::" #: ../../tutorial/datastructures.rst:305 msgid "" "As we saw in the previous section, the inner list comprehension 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 compreensão de lista interna é computada no " "contexto da cláusula :keyword:`for` seguinte, portanto o exemplo acima " "equivale a::" #: ../../tutorial/datastructures.rst:316 msgid "which, in turn, is the same as::" msgstr "e isso, por sua vez, faz o mesmo que isto::" #: ../../tutorial/datastructures.rst:329 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 " "instruções complexas. A função :func:`zip` resolve muito bem este caso de " "uso::" #: ../../tutorial/datastructures.rst:335 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:340 msgid "The :keyword:`!del` statement" msgstr "A instrução :keyword:`!del`" #: ../../tutorial/datastructures.rst:342 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:`~list." "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 usando seu índice no " "lugar do seu valor: a instrução :keyword:`del`. Ele difere do método :meth:" "`~list.pop` que devolve um valor. A instrução :keyword:`!del` pode também " "ser utilizada para remover fatias de uma lista ou limpar a lista inteira " "(que fizemos antes por atribuição de uma lista vazia à fatia ``a[:]``). Por " "exemplo::" #: ../../tutorial/datastructures.rst:359 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:363 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 até que seja feita uma nova atribuição para ela). Encontraremos outros " "usos para a instrução :keyword:`del` mais tarde." #: ../../tutorial/datastructures.rst:370 msgid "Tuples and Sequences" msgstr "Tuplas e Sequências" #: ../../tutorial/datastructures.rst:372 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 operações de fatiamento. Elas são dois exemplos de *sequências* (veja :ref:" "`typesseq`). Como Python é uma linguagem em evolução, outros tipos de " "sequências podem ser adicionados. Existe ainda um outro tipo de sequência " "padrão na linguagem: a *tupla*." #: ../../tutorial/datastructures.rst:378 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, por " "exemplo::" #: ../../tutorial/datastructures.rst:400 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 " "envolvidas por parênteses, assim tuplas aninhadas podem ser lidas " "corretamente. Na criação, tuplas podem ser envolvidas ou não por parênteses, " "desde que o contexto não exija os parênteses (como no caso da tupla dentro " "de uma expressão maior). Não é possível atribuir itens individuais de uma " "tupla, contudo é possível criar tuplas que contenham objetos mutáveis, como " "listas." #: ../../tutorial/datastructures.rst:407 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 `). Lists are :term:" "`mutable`, and their elements are usually homogeneous and are accessed by " "iterating over the list." msgstr "" "Apesar de tuplas serem similares a listas, elas são frequentemente " "utilizadas em situações diferentes e com propósitos distintos. Tuplas são :" "term:`imutáveis `, e usualmente contém uma sequência heterogênea " "de elementos que são acessados via desempacotamento (ver a seguir nessa " "seção) ou índice (ou mesmo por um atributo no caso de :func:`namedtuples " "`). Listas são :term:`mutáveis `, e seus " "elementos geralmente são homogêneos e são acessados iterando sobre a lista." #: ../../tutorial/datastructures.rst:415 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 " "usa certos truques para acomodar estes casos. Tuplas vazias são construídas " "por um par de parênteses vazios; uma tupla unitária é construída por um " "único valor seguido de uma vírgula (não basta colocar um único valor entre " "parênteses). Feio, mas funciona. Por exemplo::" #: ../../tutorial/datastructures.rst:430 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 "" "A instrução ``t = 12345, 54321, 'bom dia!'`` é um exemplo de *empacotamento " "de tupla*: os valores ``12345``, ``54321`` e ``'bom dia!'`` são empacotados " "em uma tupla. A operação inversa também é possível::" #: ../../tutorial/datastructures.rst:436 msgid "" "This is called, appropriately enough, *sequence unpacking* and works for any " "sequence on the right-hand side. Sequence unpacking requires that there are " "as many variables on the left side of the equals sign as there are elements " "in the sequence. Note that multiple assignment is really just a combination " "of tuple packing and sequence unpacking." msgstr "" "Isso é chamado, apropriadamente, de *desempacotamento de sequência* e " "funciona para qualquer sequência no lado direito. O desempacotamento de " "sequência requer que haja tantas variáveis no lado esquerdo do sinal de " "igual, quanto existem de elementos na sequência. Observe que a atribuição " "múltipla é, na verdade, apenas uma combinação de empacotamento de tupla e " "desempacotamento de sequência." #: ../../tutorial/datastructures.rst:446 msgid "Sets" msgstr "Conjuntos" #: ../../tutorial/datastructures.rst:448 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 " "conjunto é uma coleção desordenada de elementos, sem elementos repetidos. " "Usos comuns para conjuntos incluem a verificação eficiente da existência de " "objetos e a eliminação de itens duplicados. Conjuntos também suportam " "operações matemáticas como união, interseção, diferença e diferença " "simétrica." #: ../../tutorial/datastructures.rst:453 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:457 msgid "Here is a brief demonstration::" msgstr "Uma pequena demonstração::" #: ../../tutorial/datastructures.rst:482 msgid "" "Similarly to :ref:`list comprehensions `, set comprehensions " "are also supported::" msgstr "" "Da mesma forma que :ref:`compreensão de listas `, " "compreensões de conjunto também são suportadas::" #: ../../tutorial/datastructures.rst:493 msgid "Dictionaries" msgstr "Dicionários" #: ../../tutorial/datastructures.rst:495 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:" "`~list.append` and :meth:`~list.extend`." msgstr "" "Outra estrutura de dados muito útil embutida em Python é o *dicionário*, " "cujo tipo é ``dict`` (ver :ref:`typesmapping`). Dicionários são também " "chamados de “memória associativa” ou “vetor associativo” em outras " "linguagens. Diferente de sequências que são indexadas por inteiros, " "dicionários são indexados por chaves (*keys*), que podem ser de qualquer " "tipo imutável (como strings e inteiros). Tuplas também podem ser chaves se " "contiverem apenas strings, inteiros ou outras tuplas. Se a tupla contiver, " "direta ou indiretamente, qualquer valor mutável, não poderá ser chave. " "Listas não podem ser usadas como chaves porque podem ser modificadas " "*internamente* pela atribuição em índices ou fatias, e por métodos como :" "meth:`~list.append` e :meth:`~list.extend`." #: ../../tutorial/datastructures.rst:506 msgid "" "It is best to think of a dictionary as a 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 pares *chave:valor*, onde as chaves são únicas em uma dada instância do " "dicionário. Dicionários são delimitados por chaves: ``{}``, e contém uma " "lista de pares chave:valor separada por vírgulas. Dessa forma também será " "exibido o conteúdo de um dicionário no console do Python. O dicionário vazio " "é ``{}``." #: ../../tutorial/datastructures.rst:512 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 " "partir de chaves. Também é possível remover um par *chave:valor* com o " "comando ``del``. Se você armazenar um valor utilizando uma chave já " "presente, o antigo valor será substituído pelo novo. Se tentar recuperar um " "valor usando uma chave inexistente, será gerado um erro." #: ../../tutorial/datastructures.rst:518 msgid "" "Performing ``list(d)`` on a dictionary returns a list of all the keys used " "in the dictionary, in insertion order (if you want it sorted, just use " "``sorted(d)`` instead). To check whether a single key is in the dictionary, " "use the :keyword:`in` keyword." msgstr "" "Executar ``list(d)`` em um dicionário devolve a lista de todas as chaves " "presentes no dicionário, na ordem de inserção (se desejar ordená-las basta " "usar a função ``sorted(d)``). Para verificar a existência de uma chave, use " "o operador :keyword:`in`." #: ../../tutorial/datastructures.rst:523 msgid "Here is a small example using a dictionary::" msgstr "A seguir, um exemplo de uso do dicionário::" #: ../../tutorial/datastructures.rst:544 msgid "" "The :func:`dict` constructor builds dictionaries directly from sequences of " "key-value pairs::" msgstr "" "O construtor :func:`dict` produz dicionários diretamente de sequências de " "pares chave-valor::" #: ../../tutorial/datastructures.rst:550 msgid "" "In addition, dict comprehensions can be used to create dictionaries from " "arbitrary key and value expressions::" msgstr "" "Além disso, as compreensões de dicionários podem ser usadas para criar " "dicionários a partir de expressões arbitrárias de chave e valor::" #: ../../tutorial/datastructures.rst:556 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 " "argumentos nomeados no construtor::" #: ../../tutorial/datastructures.rst:566 msgid "Looping Techniques" msgstr "Técnicas de iteração" #: ../../tutorial/datastructures.rst:568 msgid "" "When looping through dictionaries, the key and corresponding value can be " "retrieved at the same time using the :meth:`~dict.items` method. ::" msgstr "" "Ao iterar sobre dicionários, a chave e o valor correspondente podem ser " "obtidos simultaneamente usando o método :meth:`~dict.items`. ::" #: ../../tutorial/datastructures.rst:578 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 iterar sobre sequências, a posição e o valor correspondente podem ser " "obtidos simultaneamente usando a função :func:`enumerate`. ::" #: ../../tutorial/datastructures.rst:588 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 ao mesmo tempo, as entradas podem ser " "pareadas com a função :func:`zip`. ::" #: ../../tutorial/datastructures.rst:600 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:612 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`, que retorna uma lista ordenada com os itens, mantendo a sequência " "original inalterada. ::" #: ../../tutorial/datastructures.rst:626 msgid "" "Using :func:`set` on a sequence eliminates duplicate elements. The use of :" "func:`sorted` in combination with :func:`set` over a sequence is an " "idiomatic way to loop over unique elements of the sequence in sorted " "order. ::" msgstr "" "Usar :func:`set` em uma sequência elimina elementos duplicados. O uso de :" "func:`sorted` em combinação com :func:`set` sobre uma sequência é uma " "maneira idiomática de fazer um loop sobre elementos exclusivos da sequência " "na ordem de classificação. ::" #: ../../tutorial/datastructures.rst:639 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:656 msgid "More on Conditions" msgstr "Mais sobre condições" #: ../../tutorial/datastructures.rst:658 msgid "" "The conditions used in ``while`` and ``if`` statements can contain any " "operators, not just comparisons." msgstr "" "As condições de controle usadas nas instruções ``while`` e ``if`` podem " "conter quaisquer operadores, não apenas comparações." #: ../../tutorial/datastructures.rst:662 msgid "" "The comparison operators ``in`` and ``not in`` are membership tests that " "determine whether a value is in (or not in) a container. The operators " "``is`` and ``is not`` compare whether two objects are really the same " "object. 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`` fazem testes de inclusão que " "determinam se um valor está (ou não está) em um contêiner. Os operadores " "``is`` e ``is not`` comparam se dois objetos são realmente o mesmo objeto. " "Todos os operadores de comparação possuem a mesma prioridade, que é menor " "que a prioridade de todos os operadores numéricos." #: ../../tutorial/datastructures.rst:668 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 que ``b`` e também se ``b`` é igual a ``c``." #: ../../tutorial/datastructures.rst:671 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 " "``or``, e o resultado de uma comparação (ou de qualquer outra expressão), " "pode ter seu valor booleano negado através de ``not``. Estes possuem menor " "prioridade que os demais operadores de comparação. Entre eles, ``not`` é o " "de maior prioridade e ``or`` o de menor. Dessa forma, a condição ``A and not " "B or C`` é equivalente a ``(A and (not B)) or C``. Naturalmente, parênteses " "podem ser usados para expressar o agrupamento desejado." #: ../../tutorial/datastructures.rst:678 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 *curto-circuito*: " "seus argumentos são avaliados da esquerda para a direita, e a avaliação " "encerra quando o resultado é determinado. Por exemplo, se ``A`` e ``C`` são " "expressões verdadeiras, mas ``B`` é falsa, então ``A and B and C`` não chega " "a avaliar a expressão ``C``. Em geral, quando usado sobre valores genéricos " "e não como booleanos, o valor do resultado de um operador curto-circuito é o " "último valor avaliado na expressão." #: ../../tutorial/datastructures.rst:685 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 para uma variável. Por exemplo::" #: ../../tutorial/datastructures.rst:693 msgid "" "Note that in Python, unlike C, assignment inside expressions must be done " "explicitly with the :ref:`walrus operator ` ``:=``. This avoids a common class of problems encountered " "in C programs: typing ``=`` in an expression when ``==`` was intended." msgstr "" "Observe que no Python, ao contrário de C, a atribuição dentro de expressões " "deve ser feita explicitamente com o :ref:`operador morsa ` ``:=``. Isso evita uma classe comum de " "problemas encontrados nos programas C: digitar ``=`` em uma expressão quando " "``==`` era o planejado." #: ../../tutorial/datastructures.rst:703 msgid "Comparing Sequences and Other Types" msgstr "Comparando sequências e outros tipos" #: ../../tutorial/datastructures.rst:704 msgid "" "Sequence objects typically 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 Unicode code point number to " "order 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 o tipo das sequências seja o mesmo. A comparação utiliza a ordem " "lexicográfica: primeiramente os dois primeiros itens são comparados, e se " "diferirem isto determinará o resultado da comparação, caso contrário os " "próximos dois itens serão comparados, e assim por diante até que se tenha " "exaurido alguma das sequências. Se em uma comparação de itens, os mesmos " "forem também sequências (aninhadas), então é disparada recursivamente outra " "comparação lexicográfica. Se todos os itens da sequência forem iguais, então " "as sequências são ditas iguais. Se uma das sequências é uma subsequência da " "outra, então a subsequência é a menor. A comparação lexicográfica de strings " "utiliza codificação Unicode para definir a ordenação. Alguns exemplos de " "comparações entre sequências do mesmo tipo::" #: ../../tutorial/datastructures.rst:724 msgid "" "Note that comparing objects of different types with ``<`` or ``>`` is legal " "provided that the objects have appropriate comparison methods. For example, " "mixed numeric types are compared according to their numeric value, so 0 " "equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, " "the interpreter will raise a :exc:`TypeError` exception." msgstr "" "Note que comparar objetos de tipos diferentes com ``<`` ou ``>`` é permitido " "desde que os objetos possuam os métodos de comparação apropriados. Por " "exemplo, tipos numéricos mistos são comparados de acordo com os seus valores " "numéricos, portanto 0 é igual a 0.0, etc. Em caso contrário, ao invés de " "fornecer uma ordenação arbitrária, o interpretador levantará um :exc:" "`TypeError`." #: ../../tutorial/datastructures.rst:732 msgid "Footnotes" msgstr "Notas de rodapé" #: ../../tutorial/datastructures.rst:733 msgid "" "Other languages may return the mutated object, which allows method chaining, " "such as ``d->insert(\"a\")->remove(\"b\")->sort();``." msgstr "" "Outras linguagens podem retornar o objeto modificado, o que permite " "encadeamento de métodos, como ``d->insert(\"a\")->remove(\"b\")->sort();``."