# Copyright (C) 2001-2024, Python Software Foundation # This file is distributed under the same license as the Python package. # # Translators: # Adrian Liaw , 2016 # Ching-Hao Liu , 2018 # KentHsu , 2016 # Liang-Bo Wang , 2015-2016 # hsiao yi , 2015 # Steven Hsu , 2021 msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-09-03 11:11+0800\n" "PO-Revision-Date: 2024-01-22 21:43+0800\n" "Last-Translator: Steven Hsu \n" "Language-Team: Chinese - TAIWAN (https://github.com/python/python-docs-zh-" "tw)\n" "Language: zh_TW\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" "X-Generator: Poedit 3.4.1\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 "進一步了解 List(串列)" #: ../../tutorial/datastructures.rst:15 msgid "" "The list data type has some more methods. Here are all of the methods of " "list objects:" msgstr "" "List(串列)這個資料型態,具有更多操作的方法。下面條列了所有關於 list 物件的 " "method:" #: ../../tutorial/datastructures.rst:22 msgid "" "Add an item to the end of the list. Equivalent to ``a[len(a):] = [x]``." msgstr "將一個新的項目加到 list 的尾端。等同於 ``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 "" "將 iterable(可疊代物件)接到 list 的尾端。等同於 ``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 "" "將一個項目插入至 list 中給定的位置。第一個引數為插入處前元素的索引值,所以 " "``a.insert(0, x)`` 會插入在 list 首位,而 ``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 "" "刪除 list 中第一個值等於 *x* 的元素。若 list 中無此元素則會觸發 :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 "" "移除 list 中給定位置的項目,並回傳它。如果沒有指定位置, ``a.pop()`` 將會移" "除 list 中最後的項目並回傳它。若 list 是空的或是索引值超出範圍,則會引發 :" "exc:`IndexError` 例外。" #: ../../tutorial/datastructures.rst:59 msgid "Remove all items from the list. Equivalent to ``del a[:]``." msgstr "刪除 list 中所有項目。這等同於 ``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 "" "回傳 list 中第一個值等於 *x* 的項目之索引值(從零開始的索引)。若 list 中無此" "項目,則丟出 :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* 的定義跟在 slice 表示法中相同,搜尋的動作被這兩個引數限" "定在 list 中特定的子序列。但要注意的是,回傳的索引值是從 list 的開頭開始算," "而不是從 *start* 開始算。" #: ../../tutorial/datastructures.rst:77 msgid "Return the number of times *x* appears in the list." msgstr "回傳 *x* 在 list 中所出現的次數。" #: ../../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 "" "將 list 中的項目排序。(可使用引數來進行客製化的排序,請參考 :func:`sorted` " "部分的解釋)" #: ../../tutorial/datastructures.rst:90 msgid "Reverse the elements of the list in place." msgstr "將 list 中的項目前後順序反過來。" #: ../../tutorial/datastructures.rst:96 msgid "Return a shallow copy of the list. Equivalent to ``a[:]``." msgstr "回傳一個淺複製 (shallow copy) 的 list。等同於 ``a[:]``。" #: ../../tutorial/datastructures.rst:99 msgid "An example that uses most of the list methods::" msgstr "以下是一個使用到許多 list 物件方法的例子: ::" #: ../../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 "" #: ../../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 "將 List 作為 Stack(堆疊)使用" #: ../../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 "" "List 的操作方法使得它非常簡單可以用來實作 stack(堆疊)。Stack 為一個遵守最後" "加入元素最先被取回(後進先出,\"last-in, first-out\")規則的資料結構。你可以" "使用方法 :meth:`~list.append` 將一個項目放到堆疊的頂層。而使用方法 :meth:" "`~list.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 "將 List 作為 Queue(佇列)使用" #: ../../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 "" "我們也可以將 list 當作 queue(佇列)使用,即最先加入元素最先被取回(先進先" "出,\"first-in, first-out\")的資料結構。然而,list 在這種使用方式下效率較" "差。使用 ``append`` 和 ``pop`` 來加入和取出尾端的元素較快,而使用 ``insert`` " "和 ``pop`` 來插入和取出頭端的元素較慢(因為其他元素都需要挪動一格)。" #: ../../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 "" "如果要實作 queue,請使用 :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 "" #: ../../tutorial/datastructures.rst:196 msgid "List Comprehensions" msgstr "List Comprehensions(串列綜合運算)" #: ../../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 "" "List comprehension(串列綜合運算)讓你可以用簡潔的方法建立 list。常見的應用是" "基於一個序列或 iterable(可疊代物件),將每一個元素經過某個運算的結果串接起來" "成為新的 list,或是建立一個子序列,其每一個元素皆滿足一個特定的條件。" #: ../../tutorial/datastructures.rst:203 msgid "For example, assume we want to create a list of squares, like::" msgstr "舉例來說,假設我們要建立一個「平方的 list」: ::" #: ../../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``,其在迴圈結束後仍然存在。我們可以這樣" "產生平方串列而不造成任何 side effects(副作用): ::" #: ../../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 "" "一個 list comprehension 的組成,是在一對方括號內,放入一個 expression(運算" "式)、一個 :keyword:`!for` 子句、再接著零個或多個 :keyword:`!for` 或 :" "keyword:`!if` 子句。結果會是一個新的 list,內容是在後面的 :keyword:`!for` " "和 :keyword:`!if` 子句情境下,對前面運算式求值的結果。例如,這個 list " "comprehension 組合了兩個 list 中彼此相異的元素: ::" #: ../../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 "" "如果 expression 是一個 tuple(例如上面例子中的 ``(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 "" #: ../../tutorial/datastructures.rst:279 msgid "" "List comprehensions can contain complex expressions and nested functions::" msgstr "List comprehensions 可以含有複雜的 expression 和巢狀的函式: ::" #: ../../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 "巢狀的 List Comprehensions" #: ../../tutorial/datastructures.rst:288 msgid "" "The initial expression in a list comprehension can be any arbitrary " "expression, including another list comprehension." msgstr "" "在 list comprehesion 中開頭的 expression 可以是任何形式的 expression,包括再" "寫一個 list comprehension。" #: ../../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 矩陣的範例,使用 list 包含 3 個長度為 4 的 list :" #: ../../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 "以下的 list comprehesion 會將矩陣的行與列作轉置: ::" #: ../../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 "" "如同我們在上一節看到的,內部的 list comprehension 會依據後面的 :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 "" #: ../../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 "" "在實際運用上,我們傾向於使用內建函式 (built-in functions) 而不是複雜的流程控" "制陳述式。在這個例子中,使用 :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:`~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 "" "有一個方法可以藉由索引而不是值來刪除 list 中的項目::keyword:`del` 陳述式。這" "和 :meth:`~list.pop` method 傳回一個值不同,:keyword:`!del` 陳述式可以用來刪" "除 list 中的片段或者清空整個 list(我們之前藉由指派一個空的 list 給想刪除的片" "段來完成這件事)。例如: ::" #: ../../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 "Tuples 和序列 (Sequences)" #: ../../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 "" "我們看到 list 和字串 (string) 有許多共同的特性,像是索引操作 (indexing) 以及" "切片操作 (slicing) 。他們是\\ *序列*\\ 資料類型中的兩個例子(請參考\\ :ref:" "`typesseq`\\ )。由於 Python 是個持續發展中的語言,未來可能還會有其他的序列資" "料類型加入。接著要介紹是下一個標準序列資料類型:*tuple*。" #: ../../tutorial/datastructures.rst:378 msgid "" "A tuple consists of a number of values separated by commas, for instance::" msgstr "一個 tuple 是由若干個值藉由逗號區隔而組成,例如: ::" #: ../../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 "" #: ../../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 "" "如同我們看到的,被輸出的 tuple 總是以括號包著,如此巢狀的 tuple 才能被正確的" "直譯 (interpret);他們可以是以被括號包著或不被包著的方式當作輸入,雖然括號的" "使用常常是有其必要的(譬如此 tuple 是一個較大的運算式的一部分)。指派東西給 " "tuple 中的個別項目是不行的,但是可以建立含有可變物件(譬如 list)的 tuple。" #: ../../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 "" "雖然 tuple 和 list 看起來很類似,但是他們通常用在不同的情況與不同目的。 " "tuple 是 :term:`immutable`\\ (不可變的),通常儲存異質的元素序列,並可經由拆" "解 (unpacking)(請參考本節後段)或索引 (indexing) 來存取(或者在使用 :func:" "`namedtuples ` 的時候藉由屬性 (attribute) 來存取)。" "List 是 :term:`mutable`\\ (可變的),其元素通常是同質的且可藉由疊代整個 " "list 來存取。" #: ../../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 個項目的 tuple:語法上會採納一些" "奇怪的用法。空的 tuple 藉由一對空括號來建立;含有一個項目的 tuple 經由一個值" "加上一個逗點來建立(用括號把一個單一的值包住是不夠的)。醜,但有效率。例" "如: ::" #: ../../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 "" #: ../../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!'`` 就是一個 *tuple packing* 的例子:" "``12345``,``54321`` 和 ``'hello!'`` 一起被放進 tuple 裡。反向操作也可以: ::" #: ../../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 "" "這個正是我們所說序列拆解 (*sequence unpacking*),可運用在任何位在等號右邊的序" "列。序列拆解要求等號左邊的變數數量必須與等號右邊的序列中的元素數量相同。注" "意,多重指派就只是 tuple packing 和序列拆解的結合而已。" #: ../../tutorial/datastructures.rst:446 msgid "Sets" msgstr "集合 (Sets)" #: ../../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 也包含了一種用在 *set*\\ (集合)的資料類型。一個 set 是一組無序且沒有" "重複的元素。基本的使用方式包括了隸屬資格檢測和消除重複元素。 Set 物件也支援聯" "集、交集、差集和互斥等數學運算。" #: ../../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。注意:要建立一個空的 set,你必須" "使用 ``set()`` 而不是 ``{}``;後者會建立一個空的 dictionary,一種我們將在下一" "節討論的資料結構。" #: ../../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 "" #: ../../tutorial/datastructures.rst:482 msgid "" "Similarly to :ref:`list comprehensions `, set comprehensions " "are also supported::" msgstr "" "和 :ref:`list comprehensions ` 類似,也有 set comprehensions" "(集合綜合運算): ::" #: ../../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 "字典(Dictionary)" #: ../../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 "" "下一個常用的 Python 內建資料類型為 *dictionary*\\ (請參考\\ :ref:" "`typesmapping`\\ )。 Dictionary 有時被稱為「關聯記憶體」(associative " "memories) 或「關聯陣列」(associative arrays)。不像序列是由一個範圍內的數字當" "作索引,dictionary 是由\\ *鍵* (key) 來當索引,鍵可以是任何不可變的類型;字串" "和數字都可以當作鍵。Tuple 也可以當作鍵,如果他們只含有字串、數字或 tuple;若" "一個 tuple 直接或間接地含有任何可變的物件,它就不能當作鍵。你無法使用 list 當" "作鍵,因為 list 可以經由索引指派 (index assignment)、切片指派 (slice " "assignment) 或是像 :meth:`~list.append` 和 :meth:`~list.extend` 等 method 被" "修改。" #: ../../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 "" "思考 dictionary 最好的方式是把它想成是一組\\ *鍵值*\\ 對 (*key: value* pair) " "的 set,其中鍵在同一個 dictionary 裡必須是獨一無二的。使用一對大括號可建立一" "個空的 dictionary:``{}``。將一串由逗號分隔的鍵值對置於大括號則可初始化字典的" "鍵值對。這同樣也是字典輸出時的格式。" #: ../../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 "" "Dictionary 主要的操作為藉由鍵來儲存一個值並且可藉由該鍵來取出該值。也可以使" "用 ``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 "" "對 dictionary 使用 ``list(d)`` 會得到一個包含該字典所有鍵的 list,其排列順序" "為插入時的順序。(若想要排序,則使用 ``sorted(d)`` 代替即可)。如果想確認一個" "鍵是否已存在於字典中,可使用關鍵字 :keyword:`in`。" #: ../../tutorial/datastructures.rst:523 msgid "Here is a small example using a dictionary::" msgstr "這是個使用一個 dictionary 的簡單範例: ::" #: ../../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` 可直接透過一串鍵值對序列來建立 dictionary: ::" #: ../../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 "" "此外,dict comprehensions 也可以透過任意鍵與值的運算式來建立 dictionary : ::" #: ../../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 "" "當鍵是簡單的字串時,使用關鍵字引數 (keyword arguments) 有時會較為簡潔: ::" #: ../../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 "" "當對 dictionary 作迴圈時,鍵以及其對應的值可以藉由使用 :meth:`~dict.items` " "method 來同時取得: ::" #: ../../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` 函式會得到一個新的經排序過的 " "list ,但不會改變原本的序列: ::" #: ../../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 "" "有時我們會想要以迴圈來改變的一個 list,但是,通常建立一個新的 list 會更簡單且" "安全: ::" #: ../../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 "深入了解條件 (Condition)" #: ../../tutorial/datastructures.rst:658 msgid "" "The conditions used in ``while`` and ``if`` statements can contain any " "operators, not just comparisons." msgstr "" "使用在 ``while`` 和 ``if`` 陳述式的條件句可以包含任何運算子,而不是只有比較運" "算子 (comparisons) 。" #: ../../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`` 也被稱為\\ *短路 (short-circuit)* 運算子:會將其" "引數從左至右進行運算,當結果出現時即結束運算。例如,若 ``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 "" "序列物件通常可以拿來和其他相同類型的物件做比較。這種比較使用\\ *詞典式 " "(lexicographical)* 順序:首先比較各自最前面的那項,若不相同,便可決定結果;若" "相同,則比較下一項,以此類推,直到其中一個序列完全用完。如果被拿出來比較的兩" "項本身又是相同的序列類型,則詞典式比較會遞迴地執行。如果兩個序列所有的項目都" "相等,則此兩個序列被認為是相等的。如果其中一個序列是另一個的子序列,則較短的" "那個序列為較小的序列。字串的詞典式順序使用 Unicode 的碼位 (code point) 編號來" "排序個別字元。以下是一些相同序列類型的比較: ::" #: ../../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 "" "其他語言可以回傳變更後的物件,這就允許 method 的串連,例如 ``d-" ">insert(\"a\")->remove(\"b\")->sort();``。"