# 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: # Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-07-25 16:03+0000\n" "PO-Revision-Date: 2025-07-18 19:59+0000\n" "Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Chinese (China) (https://app.transifex.com/python-doc/teams/5390/zh_CN/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh_CN\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../tutorial/datastructures.rst:5 msgid "Data Structures" msgstr "数据结构" #: ../../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 "本章深入讲解之前学过的一些内容,同时,还增加了新的知识点。" #: ../../tutorial/datastructures.rst:13 msgid "More on Lists" msgstr "列表详解" #: ../../tutorial/datastructures.rst:15 msgid "" "The list data type has some more methods. Here are all of the methods of " "list objects:" msgstr "列表数据类型支持很多方法,列表对象的所有方法所示如下:" #: ../../tutorial/datastructures.rst:22 msgid "Add an item to the end of the list. Similar to ``a[len(a):] = [x]``." msgstr "在列表末尾添加一项。 类似于 ``a[len(a):] = [x]``。" #: ../../tutorial/datastructures.rst:28 msgid "" "Extend the list by appending all the items from the iterable. Similar to " "``a[len(a):] = iterable``." msgstr "通过添加来自 iterable 的所有项来扩展列表。 类似于 ``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 "" "在指定位置插入元素。第一个参数是插入元素的索引,因此,``a.insert(0, x)`` 在列表开头插入元素, ``a.insert(len(a), " "x)`` 等同于 ``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 "从列表中删除第一个值为 *x* 的元素。未找到指定元素时,触发 :exc:`ValueError` 异常。" #: ../../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 "" "移除列表中给定位置上的条目,并返回该条目。 如果未指定索引号,则 ``a.pop()`` 将移除并返回列表中的最后一个条目。 " "如果列表为空或索引号在列表索引范围之外则会引发 :exc:`IndexError`。" #: ../../tutorial/datastructures.rst:59 msgid "Remove all items from the list. Similar to ``del a[:]``." msgstr "移除列表中的所有项。 类似于 ``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 "返回列表中第一个值为 *x* 的元素的零基索引。未找到指定元素时,触发 :exc:`ValueError` 异常。" #: ../../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 "" "可选参数 *start* 和 *end* 是切片符号,用于将搜索限制为列表的特定子序列。返回的索引是相对于整个序列的开始计算的,而不是 *start* " "参数。" #: ../../tutorial/datastructures.rst:77 msgid "Return the number of times *x* appears in the list." msgstr "返回列表中元素 *x* 出现的次数。" #: ../../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 "就地排序列表中的元素(要了解自定义排序参数,详见 :func:`sorted`)。" #: ../../tutorial/datastructures.rst:90 msgid "Reverse the elements of the list in place." msgstr "翻转列表中的元素。" #: ../../tutorial/datastructures.rst:96 msgid "Return a shallow copy of the list. Similar to ``a[:]``." msgstr "返回列表的浅拷贝。 类似于 ``a[:]``。" #: ../../tutorial/datastructures.rst:99 msgid "An example that uses most of the list methods::" msgstr "多数列表方法示例:" #: ../../tutorial/datastructures.rst:101 msgid "" ">>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']\n" ">>> fruits.count('apple')\n" "2\n" ">>> fruits.count('tangerine')\n" "0\n" ">>> fruits.index('banana')\n" "3\n" ">>> fruits.index('banana', 4) # Find next banana starting at position 4\n" "6\n" ">>> fruits.reverse()\n" ">>> fruits\n" "['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']\n" ">>> fruits.append('grape')\n" ">>> fruits\n" "['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']\n" ">>> fruits.sort()\n" ">>> fruits\n" "['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']\n" ">>> fruits.pop()\n" "'pear'" msgstr "" ">>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']\n" ">>> fruits.count('apple')\n" "2\n" ">>> fruits.count('tangerine')\n" "0\n" ">>> fruits.index('banana')\n" "3\n" ">>> fruits.index('banana', 4) # 从 4 号位开始查找下一个 banana\n" "6\n" ">>> fruits.reverse()\n" ">>> fruits\n" "['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']\n" ">>> fruits.append('grape')\n" ">>> fruits\n" "['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']\n" ">>> fruits.sort()\n" ">>> fruits\n" "['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']\n" ">>> fruits.pop()\n" "'pear'" #: ../../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 "" "你可能已经注意到 ``insert``, ``remove`` 或 ``sort`` 等仅修改列表的方法都不会打印返回值 -- 它们返回默认值 " "``None``。 [#]_ 这是适用于 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 "" "你可能会注意到的另一件事是并非所有数据都可以排序或比较。 举例来说,``[None, 'hello', 10]`` 就不可排序因为整数不能与字符串比较而" " ``None`` 不能与其他类型比较。 此外,还存在一些没有定义顺序关系的类型。 例如,``3+4j < 5+7j`` 就不是一个合法的比较。" #: ../../tutorial/datastructures.rst:138 msgid "Using Lists as Stacks" msgstr "用列表实现堆栈" #: ../../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:`!append`. To retrieve an " "item from the top of the stack, use :meth:`!pop` without an explicit index." " For example::" msgstr "" "列表方法使得将列表用作栈非常容易,最后添加的元素会最先被取出(“后进先出”)。 要将一个条目添加到栈顶,可使用 :meth:`!append`。 " "要从栈顶取出一个条目,则使用 :meth:`!pop` 且不必显式指定索引。 例如::" #: ../../tutorial/datastructures.rst:148 msgid "" ">>> stack = [3, 4, 5]\n" ">>> stack.append(6)\n" ">>> stack.append(7)\n" ">>> stack\n" "[3, 4, 5, 6, 7]\n" ">>> stack.pop()\n" "7\n" ">>> stack\n" "[3, 4, 5, 6]\n" ">>> stack.pop()\n" "6\n" ">>> stack.pop()\n" "5\n" ">>> stack\n" "[3, 4]" msgstr "" ">>> stack = [3, 4, 5]\n" ">>> stack.append(6)\n" ">>> stack.append(7)\n" ">>> stack\n" "[3, 4, 5, 6, 7]\n" ">>> stack.pop()\n" "7\n" ">>> stack\n" "[3, 4, 5, 6]\n" ">>> stack.pop()\n" "6\n" ">>> stack.pop()\n" "5\n" ">>> stack\n" "[3, 4]" #: ../../tutorial/datastructures.rst:168 msgid "Using Lists as Queues" msgstr "用列表实现队列" #: ../../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 "" "列表也可以用作队列,最先加入的元素,最先取出(“先进先出”);然而,列表作为队列的效率很低。因为,在列表末尾添加和删除元素非常快,但在列表开头插入或移除元素却很慢(因为所有其他元素都必须移动一位)。" #: ../../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 "实现队列最好用 :class:`collections.deque`,可以快速从两端添加或删除元素。例如:" #: ../../tutorial/datastructures.rst:181 msgid "" ">>> from collections import deque\n" ">>> queue = deque([\"Eric\", \"John\", \"Michael\"])\n" ">>> queue.append(\"Terry\") # Terry arrives\n" ">>> queue.append(\"Graham\") # Graham arrives\n" ">>> queue.popleft() # The first to arrive now leaves\n" "'Eric'\n" ">>> queue.popleft() # The second to arrive now leaves\n" "'John'\n" ">>> queue # Remaining queue in order of arrival\n" "deque(['Michael', 'Terry', 'Graham'])" msgstr "" ">>> from collections import deque\n" ">>> queue = deque([\"Eric\", \"John\", \"Michael\"])\n" ">>> queue.append(\"Terry\") # Terry 到了\n" ">>> queue.append(\"Graham\") # Graham 到了\n" ">>> queue.popleft() # 第一个到的现在走了\n" "'Eric'\n" ">>> queue.popleft() # 第二个到的现在走了\n" "'John'\n" ">>> queue # 按到达顺序排列的剩余队列\n" "deque(['Michael', 'Terry', 'Graham'])" #: ../../tutorial/datastructures.rst:196 msgid "List Comprehensions" msgstr "列表推导式" #: ../../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 "" "列表推导式创建列表的方式更简洁。常见的用法为,对序列或可迭代对象中的每个元素应用某种操作,用生成的结果创建新的列表;或用满足特定条件的元素创建子序列。" #: ../../tutorial/datastructures.rst:203 msgid "For example, assume we want to create a list of squares, like::" msgstr "例如,创建平方值的列表:" #: ../../tutorial/datastructures.rst:205 msgid "" ">>> squares = []\n" ">>> for x in range(10):\n" "... squares.append(x**2)\n" "...\n" ">>> squares\n" "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]" msgstr "" ">>> squares = []\n" ">>> for x in range(10):\n" "... squares.append(x**2)\n" "...\n" ">>> squares\n" "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]" #: ../../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 "注意,这段代码创建(或覆盖)变量 ``x``,该变量在循环结束后仍然存在。下述方法可以无副作用地计算平方列表:" #: ../../tutorial/datastructures.rst:216 msgid "squares = list(map(lambda x: x**2, range(10)))" msgstr "squares = list(map(lambda x: x**2, range(10)))" #: ../../tutorial/datastructures.rst:218 msgid "or, equivalently::" msgstr "或等价于:" #: ../../tutorial/datastructures.rst:220 msgid "squares = [x**2 for x in range(10)]" msgstr "squares = [x**2 for x in range(10)]" #: ../../tutorial/datastructures.rst:222 msgid "which is more concise and readable." msgstr "上面这种写法更简洁、易读。" #: ../../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 "" "列表推导式的方括号内包含以下内容:一个表达式,后面为一个 :keyword:`!for` 子句,然后,是零个或多个 :keyword:`!for` 或 " ":keyword:`!if` 子句。结果是由表达式依据 :keyword:`!for` 和 :keyword:`!if` 子句求值计算而得出一个新列表。" " 举例来说,以下列表推导式将两个列表中不相等的元素组合起来:" #: ../../tutorial/datastructures.rst:231 msgid "" ">>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]\n" "[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]" msgstr "" ">>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]\n" "[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]" #: ../../tutorial/datastructures.rst:234 msgid "and it's equivalent to::" msgstr "等价于:" #: ../../tutorial/datastructures.rst:236 msgid "" ">>> combs = []\n" ">>> for x in [1,2,3]:\n" "... for y in [3,1,4]:\n" "... if x != y:\n" "... combs.append((x, y))\n" "...\n" ">>> combs\n" "[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]" msgstr "" ">>> combs = []\n" ">>> for x in [1,2,3]:\n" "... for y in [3,1,4]:\n" "... if x != y:\n" "... combs.append((x, y))\n" "...\n" ">>> combs\n" "[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]" #: ../../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 "注意,上面两段代码中,:keyword:`for` 和 :keyword:`if` 的顺序相同。" #: ../../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 "表达式是元组(例如上例的 ``(x, y)``)时,必须加上括号:" #: ../../tutorial/datastructures.rst:251 msgid "" ">>> vec = [-4, -2, 0, 2, 4]\n" ">>> # create a new list with the values doubled\n" ">>> [x*2 for x in vec]\n" "[-8, -4, 0, 4, 8]\n" ">>> # filter the list to exclude negative numbers\n" ">>> [x for x in vec if x >= 0]\n" "[0, 2, 4]\n" ">>> # apply a function to all the elements\n" ">>> [abs(x) for x in vec]\n" "[4, 2, 0, 2, 4]\n" ">>> # call a method on each element\n" ">>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']\n" ">>> [weapon.strip() for weapon in freshfruit]\n" "['banana', 'loganberry', 'passion fruit']\n" ">>> # create a list of 2-tuples like (number, square)\n" ">>> [(x, x**2) for x in range(6)]\n" "[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]\n" ">>> # the tuple must be parenthesized, otherwise an error is raised\n" ">>> [x, x**2 for x in range(6)]\n" " File \"\", line 1\n" " [x, x**2 for x in range(6)]\n" " ^^^^^^^\n" "SyntaxError: did you forget parentheses around the comprehension target?\n" ">>> # flatten a list using a listcomp with two 'for'\n" ">>> vec = [[1,2,3], [4,5,6], [7,8,9]]\n" ">>> [num for elem in vec for num in elem]\n" "[1, 2, 3, 4, 5, 6, 7, 8, 9]" msgstr "" ">>> vec = [-4, -2, 0, 2, 4]\n" ">>> # 新建一个将值翻倍的列表\n" ">>> [x*2 for x in vec]\n" "[-8, -4, 0, 4, 8]\n" ">>> # 过滤列表以排除负数\n" ">>> [x for x in vec if x >= 0]\n" "[0, 2, 4]\n" ">>> # 对所有元素应用一个函数\n" ">>> [abs(x) for x in vec]\n" "[4, 2, 0, 2, 4]\n" ">>> # 在每个元素上调用一个方法\n" ">>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']\n" ">>> [weapon.strip() for weapon in freshfruit]\n" "['banana', 'loganberry', 'passion fruit']\n" ">>> # 创建一个包含 (数字, 平方) 2 元组的列表\n" ">>> [(x, x**2) for x in range(6)]\n" "[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]\n" ">>> # 元组必须加圆括号,否则会引发错误\n" ">>> [x, x**2 for x in range(6)]\n" " File \"\", line 1\n" " [x, x**2 for x in range(6)]\n" " ^^^^^^^\n" "SyntaxError: did you forget parentheses around the comprehension target?\n" ">>> # 使用两个 'for' 来展平嵌套的列表\n" ">>> vec = [[1,2,3], [4,5,6], [7,8,9]]\n" ">>> [num for elem in vec for num in elem]\n" "[1, 2, 3, 4, 5, 6, 7, 8, 9]" #: ../../tutorial/datastructures.rst:279 msgid "" "List comprehensions can contain complex expressions and nested functions::" msgstr "列表推导式可以使用复杂的表达式和嵌套函数:" #: ../../tutorial/datastructures.rst:281 msgid "" ">>> from math import pi\n" ">>> [str(round(pi, i)) for i in range(1, 6)]\n" "['3.1', '3.14', '3.142', '3.1416', '3.14159']" msgstr "" ">>> from math import pi\n" ">>> [str(round(pi, i)) for i in range(1, 6)]\n" "['3.1', '3.14', '3.142', '3.1416', '3.14159']" #: ../../tutorial/datastructures.rst:286 msgid "Nested List Comprehensions" msgstr "嵌套的列表推导式" #: ../../tutorial/datastructures.rst:288 msgid "" "The initial expression in a list comprehension can be any arbitrary " "expression, including another list comprehension." msgstr "列表推导式中的初始表达式可以是任何表达式,甚至可以是另一个列表推导式。" #: ../../tutorial/datastructures.rst:291 msgid "" "Consider the following example of a 3x4 matrix implemented as a list of 3 " "lists of length 4::" msgstr "下面这个 3x4 矩阵,由 3 个长度为 4 的列表组成:" #: ../../tutorial/datastructures.rst:294 msgid "" ">>> matrix = [\n" "... [1, 2, 3, 4],\n" "... [5, 6, 7, 8],\n" "... [9, 10, 11, 12],\n" "... ]" msgstr "" ">>> matrix = [\n" "... [1, 2, 3, 4],\n" "... [5, 6, 7, 8],\n" "... [9, 10, 11, 12],\n" "... ]" #: ../../tutorial/datastructures.rst:300 msgid "The following list comprehension will transpose rows and columns::" msgstr "下面的列表推导式可以转置行列:" #: ../../tutorial/datastructures.rst:302 msgid "" ">>> [[row[i] for row in matrix] for i in range(4)]\n" "[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" msgstr "" ">>> [[row[i] for row in matrix] for i in range(4)]\n" "[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" #: ../../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 "如我们在之前小节中看到的,内部的列表推导式是在它之后的 :keyword:`for` 的上下文中被求值的,所以这个例子等价于::" #: ../../tutorial/datastructures.rst:309 msgid "" ">>> transposed = []\n" ">>> for i in range(4):\n" "... transposed.append([row[i] for row in matrix])\n" "...\n" ">>> transposed\n" "[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" msgstr "" ">>> transposed = []\n" ">>> for i in range(4):\n" "... transposed.append([row[i] for row in matrix])\n" "...\n" ">>> transposed\n" "[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" #: ../../tutorial/datastructures.rst:316 msgid "which, in turn, is the same as::" msgstr "反过来说,也等价于:" #: ../../tutorial/datastructures.rst:318 msgid "" ">>> transposed = []\n" ">>> for i in range(4):\n" "... # the following 3 lines implement the nested listcomp\n" "... transposed_row = []\n" "... for row in matrix:\n" "... transposed_row.append(row[i])\n" "... transposed.append(transposed_row)\n" "...\n" ">>> transposed\n" "[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" msgstr "" ">>> transposed = []\n" ">>> for i in range(4):\n" "... # 以下 3 行实现了嵌套的列表组\n" "... transposed_row = []\n" "... for row in matrix:\n" "... transposed_row.append(row[i])\n" "... transposed.append(transposed_row)\n" "...\n" ">>> transposed\n" "[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" #: ../../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 "实际应用中,最好用内置函数替代复杂的流程语句。此时,:func:`zip` 函数更好用:" #: ../../tutorial/datastructures.rst:332 msgid "" ">>> list(zip(*matrix))\n" "[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]" msgstr "" ">>> list(zip(*matrix))\n" "[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]" #: ../../tutorial/datastructures.rst:335 msgid "" "See :ref:`tut-unpacking-arguments` for details on the asterisk in this line." msgstr "关于本行中星号的详细说明,参见 :ref:`tut-unpacking-arguments`。" #: ../../tutorial/datastructures.rst:340 msgid "The :keyword:`!del` statement" msgstr ":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:`!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 "" "可以按索引而不是按值从一个列表移除条目:即使用 :keyword:`del` 语句。 这不同于返回一个值的 :meth:`!pop` 方法。 " ":keyword:`!del` 语句还可被用来从列表移除切片或清空整个列表(之前我们通过将一个空列表赋值给切片实现此功能)。 例如::" #: ../../tutorial/datastructures.rst:348 msgid "" ">>> a = [-1, 1, 66.25, 333, 333, 1234.5]\n" ">>> del a[0]\n" ">>> a\n" "[1, 66.25, 333, 333, 1234.5]\n" ">>> del a[2:4]\n" ">>> a\n" "[1, 66.25, 1234.5]\n" ">>> del a[:]\n" ">>> a\n" "[]" msgstr "" ">>> a = [-1, 1, 66.25, 333, 333, 1234.5]\n" ">>> del a[0]\n" ">>> a\n" "[1, 66.25, 333, 333, 1234.5]\n" ">>> del a[2:4]\n" ">>> a\n" "[1, 66.25, 1234.5]\n" ">>> del a[:]\n" ">>> a\n" "[]" #: ../../tutorial/datastructures.rst:359 msgid ":keyword:`del` can also be used to delete entire variables::" msgstr ":keyword:`del` 也可以用来删除整个变量:" #: ../../tutorial/datastructures.rst:361 msgid ">>> del a" msgstr ">>> del a" #: ../../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 "此后,再引用 ``a`` 就会报错(直到为它赋与另一个值)。后文会介绍 :keyword:`del` 的其他用法。" #: ../../tutorial/datastructures.rst:370 msgid "Tuples and Sequences" msgstr "元组和序列" #: ../../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 "" "列表和字符串有很多共性,例如,索引和切片操作。这两种数据类型是 *序列* (参见 :ref:`typesseq`)。随着 Python " "语言的发展,其他的序列类型也被加入其中。本节介绍另一种标准序列类型:*元组*。" #: ../../tutorial/datastructures.rst:378 msgid "" "A tuple consists of a number of values separated by commas, for instance::" msgstr "元组由多个用逗号隔开的值组成,例如:" #: ../../tutorial/datastructures.rst:380 msgid "" ">>> t = 12345, 54321, 'hello!'\n" ">>> t[0]\n" "12345\n" ">>> t\n" "(12345, 54321, 'hello!')\n" ">>> # Tuples may be nested:\n" ">>> u = t, (1, 2, 3, 4, 5)\n" ">>> u\n" "((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))\n" ">>> # Tuples are immutable:\n" ">>> t[0] = 88888\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: 'tuple' object does not support item assignment\n" ">>> # but they can contain mutable objects:\n" ">>> v = ([1, 2, 3], [3, 2, 1])\n" ">>> v\n" "([1, 2, 3], [3, 2, 1])" msgstr "" ">>> t = 12345, 54321, 'hello!'\n" ">>> t[0]\n" "12345\n" ">>> t\n" "(12345, 54321, 'hello!')\n" ">>> # 元组可以嵌套:\n" ">>> u = t, (1, 2, 3, 4, 5)\n" ">>> u\n" "((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))\n" ">>> # 元组是不可变对象:\n" ">>> t[0] = 88888\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" "TypeError: 'tuple' object does not support item assignment\n" ">>> # 但它们可以包含可变对象:\n" ">>> v = ([1, 2, 3], [3, 2, 1])\n" ">>> v\n" "([1, 2, 3], [3, 2, 1])" #: ../../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 "" "输出时,元组都要由圆括号标注,这样才能正确地解释嵌套元组。输入时,圆括号可有可无,不过经常是必须的(如果元组是更大的表达式的一部分)。不允许为元组中的单个元素赋值,当然,可以创建含列表等可变对象的元组。" #: ../../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 "" "虽然,元组与列表很像,但使用场景不同,用途也不同。元组是 :term:`immutable` " "(不可变的),一般可包含异质元素序列,通过解包(见本节下文)或索引访问(如果是 :func:`namedtuples " "`,可以属性访问)。列表是 :term:`mutable` " "(可变的),列表元素一般为同质类型,可迭代访问。" #: ../../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 "" "构造 0 个或 1 " "个元素的元组比较特殊:为了适应这种情况,对句法有一些额外的改变。用一对空圆括号就可以创建空元组;只有一个元素的元组可以通过在这个元素后添加逗号来构建(圆括号里只有一个值的话不够明确)。丑陋,但是有效。例如:" #: ../../tutorial/datastructures.rst:421 msgid "" ">>> empty = ()\n" ">>> singleton = 'hello', # <-- note trailing comma\n" ">>> len(empty)\n" "0\n" ">>> len(singleton)\n" "1\n" ">>> singleton\n" "('hello',)" msgstr "" ">>> empty = ()\n" ">>> singleton = 'hello', # <-- 注意末尾的逗号\n" ">>> len(empty)\n" "0\n" ">>> len(singleton)\n" "1\n" ">>> singleton\n" "('hello',)" #: ../../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 "" "语句 ``t = 12345, 54321, 'hello!'`` 是 *元组打包* 的例子:值 ``12345``, ``54321`` 和 " "``'hello!'`` 一起被打包进元组。逆操作也可以:" #: ../../tutorial/datastructures.rst:434 msgid ">>> x, y, z = t" msgstr ">>> x, y, z = t" #: ../../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 "" "称之为 *序列解包* " "也是妥妥的,适用于右侧的任何序列。序列解包时,左侧变量与右侧序列元素的数量应相等。注意,多重赋值其实只是元组打包和序列解包的组合。" #: ../../tutorial/datastructures.rst:446 msgid "Sets" msgstr "集合" #: ../../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 还支持 *集合* " "这种数据类型。集合是由不重复元素组成的无序容器。基本用法包括成员检测、消除重复元素。集合对象支持合集、交集、差集、对称差分等数学运算。" #: ../../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 "" "创建集合用花括号或 :func:`set` 函数。注意,创建空集合只能用 ``set()``,不能用 ``{}``,``{}`` " "创建的是空字典,下一小节介绍数据结构:字典。" #: ../../tutorial/datastructures.rst:457 msgid "Here is a brief demonstration::" msgstr "以下是一些简单的示例 ::" #: ../../tutorial/datastructures.rst:459 msgid "" ">>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}\n" ">>> print(basket) # show that duplicates have been removed\n" "{'orange', 'banana', 'pear', 'apple'}\n" ">>> 'orange' in basket # fast membership testing\n" "True\n" ">>> 'crabgrass' in basket\n" "False\n" "\n" ">>> # Demonstrate set operations on unique letters from two words\n" ">>>\n" ">>> a = set('abracadabra')\n" ">>> b = set('alacazam')\n" ">>> a # unique letters in a\n" "{'a', 'r', 'b', 'c', 'd'}\n" ">>> a - b # letters in a but not in b\n" "{'r', 'd', 'b'}\n" ">>> a | b # letters in a or b or both\n" "{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}\n" ">>> a & b # letters in both a and b\n" "{'a', 'c'}\n" ">>> a ^ b # letters in a or b but not both\n" "{'r', 'd', 'b', 'm', 'z', 'l'}" msgstr "" ">>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}\n" ">>> print(basket) # 显示重复项已被移除\n" "{'orange', 'banana', 'pear', 'apple'}\n" ">>> 'orange' in basket # 快速成员检测\n" "True\n" ">>> 'crabgrass' in basket\n" "False\n" "\n" ">>> # 演示针对两个单词中独有的字母进行集合运算\n" ">>>\n" ">>> a = set('abracadabra')\n" ">>> b = set('alacazam')\n" ">>> a # a 中独有的字母\n" "{'a', 'r', 'b', 'c', 'd'}\n" ">>> a - b # 存在于 a 中但不存在于 b 中的字母\n" "{'r', 'd', 'b'}\n" ">>> a | b # 存在于 a 或 b 中或两者中皆有的字母\n" "{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}\n" ">>> a & b # 同时存在于 a 和 b 中的字母\n" "{'a', 'c'}\n" ">>> a ^ b # 存在于 a 或 b 中但非两者中皆有的字母\n" "{'r', 'd', 'b', 'm', 'z', 'l'}" #: ../../tutorial/datastructures.rst:482 msgid "" "Similarly to :ref:`list comprehensions `, set comprehensions " "are also supported::" msgstr "与 :ref:`列表推导式 ` 类似,集合也支持推导式:" #: ../../tutorial/datastructures.rst:485 msgid "" ">>> a = {x for x in 'abracadabra' if x not in 'abc'}\n" ">>> a\n" "{'r', 'd'}" msgstr "" ">>> a = {x for x in 'abracadabra' if x not in 'abc'}\n" ">>> a\n" "{'r', 'd'}" #: ../../tutorial/datastructures.rst:493 msgid "Dictionaries" msgstr "字典" #: ../../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:`!append` and :meth:`!extend`." msgstr "" "另一个常用的 Python 内置数据类型是 *字典* (参见 :ref:`typesmapping`)。 " "字典在其他编程语言中可能称为“联合内存”或“联合数组”。 与以连续整数为索引的序列不同,字典是以 *键* " "来索引的,键可以是任何不可变类型;字符串和数字总是可以作为键。 " "元组在其仅包含字符串、数字或元组时也可以作为键;如果一个元组直接或间接地包含了任何可变对象,则不可以用作键。 " "你不能使用列表作为键,因为列表可使用索引赋值、切片赋值或 :meth:`!append` 和 :meth:`!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 "" "可以把字典理解为 *键值对* 的集合,但字典的键必须是唯一的。花括号 ``{}`` " "用于创建空字典。另一种初始化字典的方式是,在花括号里输入逗号分隔的键值对,这也是字典的输出方式。" #: ../../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 "" "字典的主要用途是通过关键字存储、提取值。用 ``del`` " "可以删除键值对。用已存在的关键字存储值,与该关键字关联的旧值会被取代。通过不存在的键提取值,则会报错。" #: ../../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 "" "对字典执行 ``list(d)`` 操作,返回该字典中所有键的列表,按插入次序排列(如需排序,请使用 " "``sorted(d)``)。检查字典里是否存在某个键,使用关键字 :keyword:`in`。" #: ../../tutorial/datastructures.rst:523 msgid "Here is a small example using a dictionary::" msgstr "以下是一些字典的简单示例:" #: ../../tutorial/datastructures.rst:525 msgid "" ">>> tel = {'jack': 4098, 'sape': 4139}\n" ">>> tel['guido'] = 4127\n" ">>> tel\n" "{'jack': 4098, 'sape': 4139, 'guido': 4127}\n" ">>> tel['jack']\n" "4098\n" ">>> del tel['sape']\n" ">>> tel['irv'] = 4127\n" ">>> tel\n" "{'jack': 4098, 'guido': 4127, 'irv': 4127}\n" ">>> list(tel)\n" "['jack', 'guido', 'irv']\n" ">>> sorted(tel)\n" "['guido', 'irv', 'jack']\n" ">>> 'guido' in tel\n" "True\n" ">>> 'jack' not in tel\n" "False" msgstr "" ">>> tel = {'jack': 4098, 'sape': 4139}\n" ">>> tel['guido'] = 4127\n" ">>> tel\n" "{'jack': 4098, 'sape': 4139, 'guido': 4127}\n" ">>> tel['jack']\n" "4098\n" ">>> del tel['sape']\n" ">>> tel['irv'] = 4127\n" ">>> tel\n" "{'jack': 4098, 'guido': 4127, 'irv': 4127}\n" ">>> list(tel)\n" "['jack', 'guido', 'irv']\n" ">>> sorted(tel)\n" "['guido', 'irv', 'jack']\n" ">>> 'guido' in tel\n" "True\n" ">>> 'jack' not in tel\n" "False" #: ../../tutorial/datastructures.rst:544 msgid "" "The :func:`dict` constructor builds dictionaries directly from sequences of " "key-value pairs::" msgstr ":func:`dict` 构造函数可以直接用键值对序列创建字典:" #: ../../tutorial/datastructures.rst:547 msgid "" ">>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])\n" "{'sape': 4139, 'guido': 4127, 'jack': 4098}" msgstr "" ">>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])\n" "{'sape': 4139, 'guido': 4127, 'jack': 4098}" #: ../../tutorial/datastructures.rst:550 msgid "" "In addition, dict comprehensions can be used to create dictionaries from " "arbitrary key and value expressions::" msgstr "字典推导式可以用任意键值表达式创建字典:" #: ../../tutorial/datastructures.rst:553 msgid "" ">>> {x: x**2 for x in (2, 4, 6)}\n" "{2: 4, 4: 16, 6: 36}" msgstr "" ">>> {x: x**2 for x in (2, 4, 6)}\n" "{2: 4, 4: 16, 6: 36}" #: ../../tutorial/datastructures.rst:556 msgid "" "When the keys are simple strings, it is sometimes easier to specify pairs " "using keyword arguments::" msgstr "关键字是比较简单的字符串时,直接用关键字参数指定键值对更便捷:" #: ../../tutorial/datastructures.rst:559 msgid "" ">>> dict(sape=4139, guido=4127, jack=4098)\n" "{'sape': 4139, 'guido': 4127, 'jack': 4098}" msgstr "" ">>> dict(sape=4139, guido=4127, jack=4098)\n" "{'sape': 4139, 'guido': 4127, 'jack': 4098}" #: ../../tutorial/datastructures.rst:566 msgid "Looping Techniques" msgstr "循环的技巧" #: ../../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 "当对字典执行循环时,可以使用 :meth:`~dict.items` 方法同时提取键及其对应的值。 ::" #: ../../tutorial/datastructures.rst:571 msgid "" ">>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}\n" ">>> for k, v in knights.items():\n" "... print(k, v)\n" "...\n" "gallahad the pure\n" "robin the brave" msgstr "" ">>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}\n" ">>> for k, v in knights.items():\n" "... print(k, v)\n" "...\n" "gallahad the pure\n" "robin the brave" #: ../../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 "在序列中循环时,用 :func:`enumerate` 函数可以同时取出位置索引和对应的值:" #: ../../tutorial/datastructures.rst:581 msgid "" ">>> for i, v in enumerate(['tic', 'tac', 'toe']):\n" "... print(i, v)\n" "...\n" "0 tic\n" "1 tac\n" "2 toe" msgstr "" ">>> for i, v in enumerate(['tic', 'tac', 'toe']):\n" "... print(i, v)\n" "...\n" "0 tic\n" "1 tac\n" "2 toe" #: ../../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 "同时循环两个或多个序列时,用 :func:`zip` 函数可以将其内的元素一一匹配:" #: ../../tutorial/datastructures.rst:591 msgid "" ">>> questions = ['name', 'quest', 'favorite color']\n" ">>> answers = ['lancelot', 'the holy grail', 'blue']\n" ">>> for q, a in zip(questions, answers):\n" "... print('What is your {0}? It is {1}.'.format(q, a))\n" "...\n" "What is your name? It is lancelot.\n" "What is your quest? It is the holy grail.\n" "What is your favorite color? It is blue." msgstr "" ">>> questions = ['name', 'quest', 'favorite color']\n" ">>> answers = ['lancelot', 'the holy grail', 'blue']\n" ">>> for q, a in zip(questions, answers):\n" "... print('What is your {0}? It is {1}.'.format(q, a))\n" "...\n" "What is your name? It is lancelot.\n" "What is your quest? It is the holy grail.\n" "What is your favorite color? It is blue." #: ../../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 "为了逆向对序列进行循环,可以求出欲循环的正向序列,然后调用 :func:`reversed` 函数:" #: ../../tutorial/datastructures.rst:603 msgid "" ">>> for i in reversed(range(1, 10, 2)):\n" "... print(i)\n" "...\n" "9\n" "7\n" "5\n" "3\n" "1" msgstr "" ">>> for i in reversed(range(1, 10, 2)):\n" "... print(i)\n" "...\n" "9\n" "7\n" "5\n" "3\n" "1" #: ../../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 "按指定顺序循环序列,可以用 :func:`sorted` 函数,在不改动原序列的基础上,返回一个重新的序列:" #: ../../tutorial/datastructures.rst:615 msgid "" ">>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']\n" ">>> for i in sorted(basket):\n" "... print(i)\n" "...\n" "apple\n" "apple\n" "banana\n" "orange\n" "orange\n" "pear" msgstr "" ">>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']\n" ">>> for i in sorted(basket):\n" "... print(i)\n" "...\n" "apple\n" "apple\n" "banana\n" "orange\n" "orange\n" "pear" #: ../../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 "" "使用 :func:`set` 去除序列中的重复元素。使用 :func:`sorted` 加 :func:`set` " "则按排序后的顺序,循环遍历序列中的唯一元素:" #: ../../tutorial/datastructures.rst:630 msgid "" ">>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']\n" ">>> for f in sorted(set(basket)):\n" "... print(f)\n" "...\n" "apple\n" "banana\n" "orange\n" "pear" msgstr "" ">>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']\n" ">>> for f in sorted(set(basket)):\n" "... print(f)\n" "...\n" "apple\n" "banana\n" "orange\n" "pear" #: ../../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 "一般来说,在循环中修改列表的内容时,创建新列表比较简单,且安全:" #: ../../tutorial/datastructures.rst:642 msgid "" ">>> import math\n" ">>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]\n" ">>> filtered_data = []\n" ">>> for value in raw_data:\n" "... if not math.isnan(value):\n" "... filtered_data.append(value)\n" "...\n" ">>> filtered_data\n" "[56.2, 51.7, 55.3, 52.5, 47.8]" msgstr "" ">>> import math\n" ">>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]\n" ">>> filtered_data = []\n" ">>> for value in raw_data:\n" "... if not math.isnan(value):\n" "... filtered_data.append(value)\n" "...\n" ">>> filtered_data\n" "[56.2, 51.7, 55.3, 52.5, 47.8]" #: ../../tutorial/datastructures.rst:656 msgid "More on Conditions" msgstr "深入条件控制" #: ../../tutorial/datastructures.rst:658 msgid "" "The conditions used in ``while`` and ``if`` statements can contain any " "operators, not just comparisons." msgstr "``while`` 和 ``if`` 条件句不只可以进行比较,还可以使用任意运算符。" #: ../../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 "" "比较运算符 ``in`` 和 ``not in`` 用于执行确定一个值是否存在(或不存在)于某个容器中的成员检测。 运算符 ``is`` 和 ``is " "not`` 用于比较两个对象是否是同一个对象。 所有比较运算符的优先级都一样,且低于任何数值运算符。" #: ../../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 "比较操作支持链式操作。例如,``a < b == c`` 校验 ``a`` 是否小于 ``b``,且 ``b`` 是否等于 ``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 "" "比较操作可以用布尔运算符 ``and`` 和 ``or`` 组合,并且,比较操作(或其他布尔运算)的结果都可以用 ``not`` " "取反。这些操作符的优先级低于比较操作符;``not`` 的优先级最高, ``or`` 的优先级最低,因此,``A and not B or C`` " "等价于 ``(A and (not B)) or C``。与其他运算符操作一样,此处也可以用圆括号表示想要的组合。" #: ../../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 "" "布尔运算符 ``and`` 和 ``or`` 是所谓的 *短路* 运算符:其参数从左至右求值,一旦可以确定结果,求值就会停止。例如,如果 ``A`` 和" " ``C`` 为真,``B`` 为假,那么 ``A and B and C`` 不会对 ``C`` " "求值。用作普通值而不是布尔值时,短路运算符的返回值通常是最后一个求了值的参数。" #: ../../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 "还可以把比较运算或其它布尔表达式的结果赋值给变量,例如:" #: ../../tutorial/datastructures.rst:688 msgid "" ">>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'\n" ">>> non_null = string1 or string2 or string3\n" ">>> non_null\n" "'Trondheim'" msgstr "" ">>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'\n" ">>> non_null = string1 or string2 or string3\n" ">>> non_null\n" "'Trondheim'" #: ../../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 "" "注意,Python 与 C 不同,在表达式内部赋值必须显式使用 :ref:`海象运算符 ` ``:=``。 这避免了 C 程序中常见的问题:要在表达式中写 ``==`` 时,却写成了 ``=``。" #: ../../tutorial/datastructures.rst:703 msgid "Comparing Sequences and Other Types" msgstr "序列和其他类型的比较" #: ../../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 "" "序列对象可以与相同序列类型的其他对象比较。这种比较使用 *字典式* " "顺序:首先,比较前两个对应元素,如果不相等,则可确定比较结果;如果相等,则比较之后的两个元素,以此类推,直到其中一个序列结束。如果要比较的两个元素本身是相同类型的序列,则递归地执行字典式顺序比较。如果两个序列中所有的对应元素都相等,则两个序列相等。如果一个序列是另一个的初始子序列,则较短的序列可被视为较小(较少)的序列。" " 对于字符串来说,字典式顺序使用 Unicode 码位序号排序单个字符。下面列出了一些比较相同类型序列的例子:" #: ../../tutorial/datastructures.rst:716 msgid "" "(1, 2, 3) < (1, 2, 4)\n" "[1, 2, 3] < [1, 2, 4]\n" "'ABC' < 'C' < 'Pascal' < 'Python'\n" "(1, 2, 3, 4) < (1, 2, 4)\n" "(1, 2) < (1, 2, -1)\n" "(1, 2, 3) == (1.0, 2.0, 3.0)\n" "(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)" msgstr "" "(1, 2, 3) < (1, 2, 4)\n" "[1, 2, 3] < [1, 2, 4]\n" "'ABC' < 'C' < 'Pascal' < 'Python'\n" "(1, 2, 3, 4) < (1, 2, 4)\n" "(1, 2) < (1, 2, -1)\n" "(1, 2, 3) == (1.0, 2.0, 3.0)\n" "(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)" #: ../../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 "" "注意,当比较不同类型的对象时,只要待比较的对象提供了合适的比较方法,就可以使用 ``<`` 和 ``>`` " "进行比较。例如,混合的数字类型通过数字值进行比较,所以,0 等于 0.0,等等。如果没有提供合适的比较方法,解释器不会随便给出一个比较结果,而是引发 " ":exc:`TypeError` 异常。" #: ../../tutorial/datastructures.rst:732 msgid "Footnotes" msgstr "备注" #: ../../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 "别的语言可能会将可变对象返回,允许方法连续执行,例如 ``d->insert(\"a\")->remove(\"b\")->sort();``。"