# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001-2022, Python Software Foundation # This file is distributed under the same license as the Python package. # # Translators: # 周 忠毅 , 2016 # Adrian Liaw , 2018 # Matt Wang , 2022 msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2023-07-17 17:39+0800\n" "PO-Revision-Date: 2023-02-18 14:48+0800\n" "Last-Translator: Matt Wang \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.2.2\n" #: ../../library/collections.rst:2 msgid ":mod:`collections` --- Container datatypes" msgstr ":mod:`collections` --- 容器資料型態" #: ../../library/collections.rst:10 msgid "**Source code:** :source:`Lib/collections/__init__.py`" msgstr "**原始碼:**\\ :source:`Lib/collections/__init__.py`" #: ../../library/collections.rst:20 msgid "" "This module implements specialized container datatypes providing " "alternatives to Python's general purpose built-in containers, :class:" "`dict`, :class:`list`, :class:`set`, and :class:`tuple`." msgstr "" "這個模組實作了一些特別的容器資料型態,用來替代 Python 一般內建的容器,例如 :" "class:`dict`\\ (字典)、\\ :class:`list`\\ (串列)、\\ :class:`set`\\ (集" "合)和 :class:`tuple`\\ (元組)。" #: ../../library/collections.rst:25 msgid ":func:`namedtuple`" msgstr ":func:`namedtuple`" #: ../../library/collections.rst:25 msgid "factory function for creating tuple subclasses with named fields" msgstr "用來建立具名欄位的 tuple 子類別的工廠函式" #: ../../library/collections.rst:26 msgid ":class:`deque`" msgstr ":class:`deque`" #: ../../library/collections.rst:26 msgid "list-like container with fast appends and pops on either end" msgstr "" "一個類似 list 的容器,可以快速的在頭尾加入 (append) 元素與移除 (pop) 元素" #: ../../library/collections.rst:27 msgid ":class:`ChainMap`" msgstr ":class:`ChainMap`" #: ../../library/collections.rst:27 msgid "dict-like class for creating a single view of multiple mappings" msgstr "一個類似 dict 的類別,用來為多個對映 (mapping) 建立單一的視圖 (view)" #: ../../library/collections.rst:28 msgid ":class:`Counter`" msgstr ":class:`Counter`" #: ../../library/collections.rst:28 msgid "dict subclass for counting :term:`hashable` objects" msgstr "dict 的子類別,用來計算\\ :term:`可雜湊 `\\ 物件的數量" #: ../../library/collections.rst:29 msgid ":class:`OrderedDict`" msgstr ":class:`OrderedDict`" #: ../../library/collections.rst:29 msgid "dict subclass that remembers the order entries were added" msgstr "dict 的子類別,會記錄物件被加入的順序" #: ../../library/collections.rst:30 msgid ":class:`defaultdict`" msgstr ":class:`defaultdict`" #: ../../library/collections.rst:30 msgid "dict subclass that calls a factory function to supply missing values" msgstr "dict 的子類別,當值不存在 dict 中時會呼叫一個提供預設值的工廠函式" #: ../../library/collections.rst:31 msgid ":class:`UserDict`" msgstr ":class:`UserDict`" #: ../../library/collections.rst:31 msgid "wrapper around dictionary objects for easier dict subclassing" msgstr "dict 物件的包裝器 (wrapper),簡化了 dict 的子類別化過程" #: ../../library/collections.rst:32 msgid ":class:`UserList`" msgstr ":class:`UserList`" #: ../../library/collections.rst:32 msgid "wrapper around list objects for easier list subclassing" msgstr "list 物件的包裝器,簡化了 list 的子類別化過程" #: ../../library/collections.rst:33 msgid ":class:`UserString`" msgstr ":class:`UserString`" #: ../../library/collections.rst:33 msgid "wrapper around string objects for easier string subclassing" msgstr "字串物件的包裝器,簡化了字串的子類別化過程" #: ../../library/collections.rst:38 msgid ":class:`ChainMap` objects" msgstr ":class:`ChainMap` 物件" #: ../../library/collections.rst:42 msgid "" "A :class:`ChainMap` class is provided for quickly linking a number of " "mappings so they can be treated as a single unit. It is often much faster " "than creating a new dictionary and running multiple :meth:`~dict.update` " "calls." msgstr "" ":class:`ChainMap`\\ (對映鏈結)類別的目的是快速將數個對映連結在一起,讓它們" "可以被當作一個單元來處理。它通常會比建立一個新的字典並多次呼叫 :meth:`~dict." "update` 來得更快。" #: ../../library/collections.rst:46 msgid "" "The class can be used to simulate nested scopes and is useful in templating." msgstr "" "這個類別可用於模擬巢狀作用域 (nested scopes),且在模板化 (templating) 時能派" "上用場。" #: ../../library/collections.rst:50 msgid "" "A :class:`ChainMap` groups multiple dicts or other mappings together to " "create a single, updateable view. If no *maps* are specified, a single " "empty dictionary is provided so that a new chain always has at least one " "mapping." msgstr "" "一個 :class:`ChainMap` 將多個 dict 或其他對映組合在一起,建立一個獨立、可更新" "的視圖。如果沒有指定 *maps*,預設會提供一個空字典讓每個新鏈結都至少有一個對" "映。" #: ../../library/collections.rst:54 msgid "" "The underlying mappings are stored in a list. That list is public and can " "be accessed or updated using the *maps* attribute. There is no other state." msgstr "" "底層的對映儲存於一個 list 中,這個 list 是公開的且可透過 *maps* 屬性存取或更" "新,沒有其他狀態 (state)。" #: ../../library/collections.rst:57 msgid "" "Lookups search the underlying mappings successively until a key is found. " "In contrast, writes, updates, and deletions only operate on the first " "mapping." msgstr "" "檢索 (lookup) 陸續查詢底層對映,直到鍵被找到,然而讀取、更新和刪除就只會對第" "一個對映操作。" #: ../../library/collections.rst:60 msgid "" "A :class:`ChainMap` incorporates the underlying mappings by reference. So, " "if one of the underlying mappings gets updated, those changes will be " "reflected in :class:`ChainMap`." msgstr "" ":class:`ChainMap` 透過參照將底層對映合併,所以當一個底層對映被更新,這些改變" "也會反映到 :class:`ChainMap`。" #: ../../library/collections.rst:64 msgid "" "All of the usual dictionary methods are supported. In addition, there is a " "*maps* attribute, a method for creating new subcontexts, and a property for " "accessing all but the first mapping:" msgstr "" "所有常見的字典方法都有支援。此外,還有一個 *maps* 屬性 (attribute)、一個建立" "子上下文 (subcontext) 的方法、和一個能夠存取除了第一個以外其他所有對映的特性 " "(property):" #: ../../library/collections.rst:70 msgid "" "A user updateable list of mappings. The list is ordered from first-searched " "to last-searched. It is the only stored state and can be modified to change " "which mappings are searched. The list should always contain at least one " "mapping." msgstr "" "一個可被更新的對映列表,這個列表是按照被搜索的順序來排列,在 ChainMap 中它是" "唯一被儲存的狀態,可被修改來變換搜索順序。回傳的列表都至少包含一個對映。" #: ../../library/collections.rst:77 msgid "" "Returns a new :class:`ChainMap` containing a new map followed by all of the " "maps in the current instance. If ``m`` is specified, it becomes the new map " "at the front of the list of mappings; if not specified, an empty dict is " "used, so that a call to ``d.new_child()`` is equivalent to: ``ChainMap({}, " "*d.maps)``. If any keyword arguments are specified, they update passed map " "or new empty dict. This method is used for creating subcontexts that can be " "updated without altering values in any of the parent mappings." msgstr "" "回傳包含一個新對映的 :class:`ChainMap`, 新對映後面接著當前實例的所有現存對" "映。如果有給定 ``m``,``m`` 會成為那個最前面的新對映;若沒有指定,則會加上一" "個空 dict,如此一來呼叫 ``d.new_child()`` 就等同於 ``ChainMap({}, *d." "maps)``。這個方法用於建立子上下文,而保持父對映的不變。" #: ../../library/collections.rst:86 msgid "The optional ``m`` parameter was added." msgstr "加入可選參數 ``m``\\ 。" #: ../../library/collections.rst:89 msgid "Keyword arguments support was added." msgstr "增加了對關鍵字引數的支援。" #: ../../library/collections.rst:94 msgid "" "Property returning a new :class:`ChainMap` containing all of the maps in the " "current instance except the first one. This is useful for skipping the " "first map in the search. Use cases are similar to those for the :keyword:" "`nonlocal` keyword used in :term:`nested scopes `. The use " "cases also parallel those for the built-in :func:`super` function. A " "reference to ``d.parents`` is equivalent to: ``ChainMap(*d.maps[1:])``." msgstr "" "回傳一個包含除了第一個以外所有其他對映的新 :class:`ChainMap` 的特性,可用於需" "要跳過第一個對映的搜索。使用情境類似於在\\ :term:`巢狀作用域 `\\ 當中使用 :keyword:`nonlocal` 關鍵字,也可與內建函式 :func:`super` " "做類比。引用 ``d.parents`` 等同於 ``ChainMap(*d.maps[1:])``。" #: ../../library/collections.rst:102 msgid "" "Note, the iteration order of a :class:`ChainMap()` is determined by scanning " "the mappings last to first::" msgstr "" "注意,一個 :class:`ChainMap()` 的疊代順序是透過由後往前掃描對映而定:\n" "\n" "::" #: ../../library/collections.rst:110 msgid "" "This gives the same ordering as a series of :meth:`dict.update` calls " "starting with the last mapping::" msgstr "" "這和呼叫 :meth:`dict.update` 結果的順序一樣是從最後一個對映開始:\n" "\n" "::" #: ../../library/collections.rst:118 msgid "Added support for ``|`` and ``|=`` operators, specified in :pep:`584`." msgstr "支援 ``|`` 和 ``|=`` 運算子,詳見 :pep:`584`。" #: ../../library/collections.rst:123 msgid "" "The `MultiContext class `_ in the Enthought `CodeTools package " "`_ has options to support writing to " "any mapping in the chain." msgstr "" "Enthought `CodeTools package `_ 中的 " "`MultiContext class `_ 支援在鏈中選定任意對映寫入。" #: ../../library/collections.rst:129 msgid "" "Django's `Context class `_ for templating is a read-only chain of mappings. It " "also features pushing and popping of contexts similar to the :meth:" "`~collections.ChainMap.new_child` method and the :attr:`~collections." "ChainMap.parents` property." msgstr "" "Django 中用於模板的 `Context class `_ 是唯讀的對映鏈,也具有加入 (push) 和移除 " "(pop) 上下文的功能,與 :meth:`~collections.ChainMap.new_child` 方法和 :attr:" "`~collections.ChainMap.parents` 特性類似。" #: ../../library/collections.rst:136 msgid "" "The `Nested Contexts recipe `_ " "has options to control whether writes and other mutations apply only to the " "first mapping or to any mapping in the chain." msgstr "" "`Nested Contexts recipe `_ 提供" "了控制是否只對鏈中第一個或其他對映做寫入或其他操作的選項。" #: ../../library/collections.rst:141 msgid "" "A `greatly simplified read-only version of Chainmap `_." msgstr "" "一個\\ `極度簡化、維讀版本的 Chainmap `_。" #: ../../library/collections.rst:146 msgid ":class:`ChainMap` Examples and Recipes" msgstr ":class:`ChainMap` 範例和用法" #: ../../library/collections.rst:148 msgid "This section shows various approaches to working with chained maps." msgstr "此章節提供了多種操作 ChainMap 的案例。" #: ../../library/collections.rst:151 msgid "Example of simulating Python's internal lookup chain::" msgstr "" "模擬 Python 內部檢索鏈結的例子:\n" "\n" "::" #: ../../library/collections.rst:156 msgid "" "Example of letting user specified command-line arguments take precedence " "over environment variables which in turn take precedence over default " "values::" msgstr "" "讓使用者指定的命令列引數優先於環境變數、再優先於預設值的範例:\n" "\n" "::" #: ../../library/collections.rst:173 msgid "" "Example patterns for using the :class:`ChainMap` class to simulate nested " "contexts::" msgstr "" "用 :class:`ChainMap` 類別模擬巢狀上下文的範例模式:\n" "\n" "::" #: ../../library/collections.rst:192 msgid "" "The :class:`ChainMap` class only makes updates (writes and deletions) to the " "first mapping in the chain while lookups will search the full chain. " "However, if deep writes and deletions are desired, it is easy to make a " "subclass that updates keys found deeper in the chain::" msgstr "" ":class:`ChainMap` 類別只對鏈結中第一個對映來做寫入或刪除,但檢索則會掃過整個" "鏈結。但如果需要對更深層的鍵寫入或刪除,透過定義一個子類別來實作也不困難:\n" "\n" "::" #: ../../library/collections.rst:223 msgid ":class:`Counter` objects" msgstr ":class:`Counter` 物件" #: ../../library/collections.rst:225 msgid "" "A counter tool is provided to support convenient and rapid tallies. For " "example::" msgstr "" "提供一個支援方便且快速計數的計數器工具,例如:\n" "\n" "::" #: ../../library/collections.rst:245 msgid "" "A :class:`Counter` is a :class:`dict` subclass for counting :term:`hashable` " "objects. It is a collection where elements are stored as dictionary keys and " "their counts are stored as dictionary values. Counts are allowed to be any " "integer value including zero or negative counts. The :class:`Counter` class " "is similar to bags or multisets in other languages." msgstr "" ":class:`Counter` 是 :class:`dict` 的子類別,用來計算\\ :term:`可雜湊 " "`\\ 物件的數量。它是將物件與其計數作為字典的鍵值對儲存的集合容器。" "計數可以是包含 0 與負數的任何整數值。:class:`Counter` 類別類似其他程式語言中" "的 bags 或 multisets。" #: ../../library/collections.rst:251 msgid "" "Elements are counted from an *iterable* or initialized from another " "*mapping* (or counter):" msgstr "" "被計數的元素來自一個 *iterable* 或是被其他的 *mapping*\\ (或 Counter)初始" "化:" #: ../../library/collections.rst:259 msgid "" "Counter objects have a dictionary interface except that they return a zero " "count for missing items instead of raising a :exc:`KeyError`:" msgstr "" "Counter 物件擁有一個字典的使用介面,除了遇到 Counter 中沒有的值時會回傳計數 " "0 取代 :exc:`KeyError` 這點不同:" #: ../../library/collections.rst:266 msgid "" "Setting a count to zero does not remove an element from a counter. Use " "``del`` to remove it entirely:" msgstr "" "將一個值的計數設為 0 並不會真的從 Counter 中刪除這個元素,要使用 ``del`` 來將" "其刪除:" #: ../../library/collections.rst:274 msgid "" "As a :class:`dict` subclass, :class:`Counter` inherited the capability to " "remember insertion order. Math operations on *Counter* objects also " "preserve order. Results are ordered according to when an element is first " "encountered in the left operand and then by the order encountered in the " "right operand." msgstr "" "作為 :class:`dict` 的子類別,\\ :class:`Counter` 繼承了記憶插入順序的功能。" "對 *Counter* 做數學運算後同樣保留順序性,其結果是依照各個元素在運算元左邊出現" "的時間先後、再按照運算元右邊出現的時間先後來排列。" #: ../../library/collections.rst:280 msgid "" "Counter objects support additional methods beyond those available for all " "dictionaries:" msgstr "除了字典原本就有的方法外,Counter 物件額外支援數個新方法:" #: ../../library/collections.rst:285 msgid "" "Return an iterator over elements repeating each as many times as its count. " "Elements are returned in the order first encountered. If an element's count " "is less than one, :meth:`elements` will ignore it." msgstr "" "回傳每個元素都重複出現計算次數的 iterator(疊代器)物件,其中元素的回傳順序是" "依照各元素首次出現的時間先後。如果元素的出現次數小於 1,\\ :meth:`elements` " "方法會忽略這些元素。" #: ../../library/collections.rst:295 msgid "" "Return a list of the *n* most common elements and their counts from the most " "common to the least. If *n* is omitted or ``None``, :meth:`most_common` " "returns *all* elements in the counter. Elements with equal counts are " "ordered in the order first encountered:" msgstr "" "回傳一個 list,包含出現最多次的 *n* 個元素及其出現次數,並按照出現次數排序。" "如果 *n* 被省略或者為 ``None``\\ ,\\ :meth:`most_common` 會回傳\\ *所有* " "counter 中的元素。出現次數相同的元素會按照首次出現的時間先後來排列:" #: ../../library/collections.rst:305 msgid "" "Elements are subtracted from an *iterable* or from another *mapping* (or " "counter). Like :meth:`dict.update` but subtracts counts instead of " "replacing them. Both inputs and outputs may be zero or negative." msgstr "" "減去自一個 *iterable* 或另一個\\ *對映*\\ (或 Counter)中的計數元素,行為類" "似 :meth:`dict.update` 但是是為了減去計數而非取代其值。輸入和輸出都可以是 0 " "或是負數。" #: ../../library/collections.rst:319 msgid "Compute the sum of the counts." msgstr "計算總計數值。" #: ../../library/collections.rst:327 msgid "" "The usual dictionary methods are available for :class:`Counter` objects " "except for two which work differently for counters." msgstr "" "通常來說字典方法也可以用於 :class:`Counter` 物件,除了以下兩個作用方式與計數" "器不同。" #: ../../library/collections.rst:332 msgid "This class method is not implemented for :class:`Counter` objects." msgstr "此類別方法沒有被實作於 :class:`Counter` 物件中。" #: ../../library/collections.rst:336 msgid "" "Elements are counted from an *iterable* or added-in from another *mapping* " "(or counter). Like :meth:`dict.update` but adds counts instead of replacing " "them. Also, the *iterable* is expected to be a sequence of elements, not a " "sequence of ``(key, value)`` pairs." msgstr "" "加上自一個 *iterable* 計算出的計數或加上另一個 *mapping*\\ (或 Counter)中的" "計數,行為類似 :meth:`dict.update` 但是是為了加上計數而非取代其值。另外,\\ " "*iterable* 需要是一串將被計算個數元素的序列,而非元素為 ``(key, value)`` 形式" "的序列。" #: ../../library/collections.rst:341 msgid "" "Counters support rich comparison operators for equality, subset, and " "superset relationships: ``==``, ``!=``, ``<``, ``<=``, ``>``, ``>=``. All of " "those tests treat missing elements as having zero counts so that " "``Counter(a=1) == Counter(a=1, b=0)`` returns true." msgstr "" "Counter 支援相等性、子集和超集關係的 rich comparison 運算子:``==``、``!=``、" "``<``、``<=``、``>``、``>=``。這些檢測會將不存在的元素之計數值當作零,因此 " "``Counter(a=1) == Counter(a=1, b=0)`` 將回傳真值。" #: ../../library/collections.rst:346 msgid "Rich comparison operations were added." msgstr "增加了 rich comparison 運算。" #: ../../library/collections.rst:349 msgid "" "In equality tests, missing elements are treated as having zero counts. " "Formerly, ``Counter(a=3)`` and ``Counter(a=3, b=0)`` were considered " "distinct." msgstr "" "在相等性運算中,不存在的元素之計數值會被當作零。在此之前,``Counter(a=3)`` " "和 ``Counter(a=3, b=0)`` 被視為不同。" #: ../../library/collections.rst:354 msgid "Common patterns for working with :class:`Counter` objects::" msgstr "" "使用 :class:`Counter` 物件的常見使用模式:\n" "\n" "::" #: ../../library/collections.rst:366 msgid "" "Several mathematical operations are provided for combining :class:`Counter` " "objects to produce multisets (counters that have counts greater than zero). " "Addition and subtraction combine counters by adding or subtracting the " "counts of corresponding elements. Intersection and union return the minimum " "and maximum of corresponding counts. Equality and inclusion compare " "corresponding counts. Each operation can accept inputs with signed counts, " "but the output will exclude results with counts of zero or less." msgstr "" "為結合多個 :class:`Counter` 物件以產生 multiset(多重集合,擁有大於 0 計數元" "素的計數器),有提供了幾種數學操作。加法和減法是根據各個對應元素分別將 " "Counter 加上和減去計數,交集和聯集分別回傳各個元素最小和最大計數,相等性與包" "含性運算則會比較對應的計數。每一個操作都可以接受輸入帶有正負號的計數,但輸出" "的 Counter 則會將擁有小於或等於 0 計數的元素剔除。" #: ../../library/collections.rst:391 msgid "" "Unary addition and subtraction are shortcuts for adding an empty counter or " "subtracting from an empty counter." msgstr "加減法的一元運算子分別是加上空的 Counter 和從空 Counter 減去的簡寫。" #: ../../library/collections.rst:400 msgid "" "Added support for unary plus, unary minus, and in-place multiset operations." msgstr "開始支援加減一元運算子和 multiset 的原地 (in-place) 操作。" #: ../../library/collections.rst:405 msgid "" "Counters were primarily designed to work with positive integers to represent " "running counts; however, care was taken to not unnecessarily preclude use " "cases needing other types or negative values. To help with those use cases, " "this section documents the minimum range and type restrictions." msgstr "" "Counter 主要是被設計來操作正整數以當作使用中的計數,但為了某些會用到計數之值" "為負數或為其他型別的案例中,Counter 也小心地被設計成不會預先排除這些特殊元" "素。為了輔助使用於上述案例,這一小節記錄了最小範圍和型別限制。" #: ../../library/collections.rst:410 msgid "" "The :class:`Counter` class itself is a dictionary subclass with no " "restrictions on its keys and values. The values are intended to be numbers " "representing counts, but you *could* store anything in the value field." msgstr "" ":class:`Counter` 類別本身是字典的子類別,且不限制其鍵與值。值被用來表示計數," "但實際上你\\ *可以*\\ 儲存任何值。" #: ../../library/collections.rst:414 msgid "" "The :meth:`~Counter.most_common` method requires only that the values be " "orderable." msgstr "使用 :meth:`~Counter.most_common` 方法的唯一條件是其值要是可被排序的。" #: ../../library/collections.rst:416 msgid "" "For in-place operations such as ``c[key] += 1``, the value type need only " "support addition and subtraction. So fractions, floats, and decimals would " "work and negative values are supported. The same is also true for :meth:" "`~Counter.update` and :meth:`~Counter.subtract` which allow negative and " "zero values for both inputs and outputs." msgstr "" "像是 ``c[key] += 1`` 的原地操作中,其值之型別只必須支援加減,所以分數、浮點" "數、十進位數與其負值都可以使用。同理,\\ :meth:`~Counter.update` 和 :meth:" "`~Counter.subtract` 也都允許 0 或負值為輸入或輸出。" #: ../../library/collections.rst:422 msgid "" "The multiset methods are designed only for use cases with positive values. " "The inputs may be negative or zero, but only outputs with positive values " "are created. There are no type restrictions, but the value type needs to " "support addition, subtraction, and comparison." msgstr "" "Multiset 相關方法只為了處理正值而設計,其輸入允許是 0 或負值但只有正值會被輸" "出。並無型別限制,但其值的型別須支援加、減及比較運算。" #: ../../library/collections.rst:427 msgid "" "The :meth:`~Counter.elements` method requires integer counts. It ignores " "zero and negative counts." msgstr ":meth:`~Counter.elements` 方法需要其計數為正值,如為 0 或負值則忽略。" #: ../../library/collections.rst:432 msgid "" "`Bag class `_ in Smalltalk." msgstr "" "Smalltalk 中的 `Bag class `_\\ 。" #: ../../library/collections.rst:435 msgid "" "Wikipedia entry for `Multisets `_." msgstr "" "維基百科上的\\ `多重集合 `_\\ 條目。" #: ../../library/collections.rst:437 msgid "" "`C++ multisets `_ tutorial with examples." msgstr "" "`C++ multisets `_ 教學與範例。" #: ../../library/collections.rst:440 msgid "" "For mathematical operations on multisets and their use cases, see *Knuth, " "Donald. The Art of Computer Programming Volume II, Section 4.6.3, Exercise " "19*." msgstr "" "Multiset 的數學運算及其使用時機,參考 *Knuth, Donald. The Art of Computer " "Programming Volume II, Section 4.6.3, Exercise 19*\\ 。" #: ../../library/collections.rst:444 msgid "" "To enumerate all distinct multisets of a given size over a given set of " "elements, see :func:`itertools.combinations_with_replacement`::" msgstr "" "若要根據給定的元素集合來列舉出所有不重複且擁有指定元素數量的 multiset,請見 :" "func:`itertools.combinations_with_replacement`\\ :\n" "\n" "::" #: ../../library/collections.rst:451 msgid ":class:`deque` objects" msgstr ":class:`deque` 物件" #: ../../library/collections.rst:455 msgid "" "Returns a new deque object initialized left-to-right (using :meth:`append`) " "with data from *iterable*. If *iterable* is not specified, the new deque is " "empty." msgstr "" "回傳一個新的 deque(雙端佇列)物件,將 *iterable* 中的資料由左至右(使用 :" "meth:`append`\\ )加入來做初始化。如果 *iterable* 並未給定,回傳的則是一個空" "的 deque。" #: ../../library/collections.rst:458 msgid "" "Deques are a generalization of stacks and queues (the name is pronounced " "\"deck\" and is short for \"double-ended queue\"). Deques support thread-" "safe, memory efficient appends and pops from either side of the deque with " "approximately the same O(1) performance in either direction." msgstr "" "Deque(發音為 \"deck\",為 \"double-ended queue\" 的簡稱)為 stack 和 queue " "的一般化。deque 支援執行緒安全 (thread-safe),且能夠有效率地節省記憶體在頭和" "尾加入和移除元素,兩個方向的表現都大致為 O(1) 複雜度。" #: ../../library/collections.rst:463 msgid "" "Though :class:`list` objects support similar operations, they are optimized " "for fast fixed-length operations and incur O(n) memory movement costs for " "``pop(0)`` and ``insert(0, v)`` operations which change both the size and " "position of the underlying data representation." msgstr "" "雖然 :class:`list` 物件也支援類似操作,但 list 優化了長度固定時的操作,而會改" "變底層資料的長度及位置的 ``pop(0)`` 和 ``insert(0, v)`` 操作,記憶體移動則為 " "O(n) 複雜度。" #: ../../library/collections.rst:469 msgid "" "If *maxlen* is not specified or is ``None``, deques may grow to an arbitrary " "length. Otherwise, the deque is bounded to the specified maximum length. " "Once a bounded length deque is full, when new items are added, a " "corresponding number of items are discarded from the opposite end. Bounded " "length deques provide functionality similar to the ``tail`` filter in Unix. " "They are also useful for tracking transactions and other pools of data where " "only the most recent activity is of interest." msgstr "" "如果 *maxlen* 沒有給定或者為 ``None``,deque 可以增長到任意長度;但若有給定的" "話,deque 的最大長度就會被限制。一個被限制長度的 deque 一但滿了,若在一端加入" "數個新元素,則同時會在另一端移除相同數量的元素。限定長度的 deque 提供了和 " "Unix ``tail`` filter 類似的功能,可用於追蹤使用者在意的那些最新執行事項或數據" "源。" #: ../../library/collections.rst:478 msgid "Deque objects support the following methods:" msgstr "Deque 物件支援以下方法:" #: ../../library/collections.rst:482 msgid "Add *x* to the right side of the deque." msgstr "將 *x* 自 deque 的右側加入。" #: ../../library/collections.rst:487 msgid "Add *x* to the left side of the deque." msgstr "將 *x* 自 deque 的左側加入。" #: ../../library/collections.rst:492 msgid "Remove all elements from the deque leaving it with length 0." msgstr "將所有元素從 deque 中移除,使其長度為 0。" #: ../../library/collections.rst:497 msgid "Create a shallow copy of the deque." msgstr "建立一個 deque 的淺複製 (shallow copy)。" #: ../../library/collections.rst:504 msgid "Count the number of deque elements equal to *x*." msgstr "計算 deque 內元素為 *x* 的個數。" #: ../../library/collections.rst:511 msgid "" "Extend the right side of the deque by appending elements from the iterable " "argument." msgstr "將 iterable 引數加入 deque 的右側。" #: ../../library/collections.rst:517 msgid "" "Extend the left side of the deque by appending elements from *iterable*. " "Note, the series of left appends results in reversing the order of elements " "in the iterable argument." msgstr "" "將 iterable 引數加入 deque 的左側。要注意的是,加入後的元素順序和 iterable 參" "數是相反的。" #: ../../library/collections.rst:524 msgid "" "Return the position of *x* in the deque (at or after index *start* and " "before index *stop*). Returns the first match or raises :exc:`ValueError` " "if not found." msgstr "" "回傳 deque 中 *x* 的位置(或在索引 *start* 之後、索引 *stop* 之前的位置)。回" "傳第一個匹配的位置,如果沒找到就引發 :exc:`ValueError`\\ 。" #: ../../library/collections.rst:533 msgid "Insert *x* into the deque at position *i*." msgstr "在 deque 位置 *i* 中插入 *x*\\ 。" #: ../../library/collections.rst:535 msgid "" "If the insertion would cause a bounded deque to grow beyond *maxlen*, an :" "exc:`IndexError` is raised." msgstr "" "如果此插入操作導致 deque 超過其長度上限 *maxlen* 的話,會引發 :exc:" "`IndexError` 例外。" #: ../../library/collections.rst:543 msgid "" "Remove and return an element from the right side of the deque. If no " "elements are present, raises an :exc:`IndexError`." msgstr "" "移除並回傳 deque 的最右側元素,若本來就沒有任何元素,則會引發 :exc:" "`IndexError`\\ 。" #: ../../library/collections.rst:549 msgid "" "Remove and return an element from the left side of the deque. If no elements " "are present, raises an :exc:`IndexError`." msgstr "" "移除並回傳 deque 的最左側元素,若本來就沒有任何元素,則會引發 :exc:" "`IndexError`\\ 。" #: ../../library/collections.rst:555 msgid "" "Remove the first occurrence of *value*. If not found, raises a :exc:" "`ValueError`." msgstr "" "移除第一個出現的 *value*\\ ,如果沒找到的話就引發一個 :exc:`ValueError`\\ 。" #: ../../library/collections.rst:561 msgid "Reverse the elements of the deque in-place and then return ``None``." msgstr "將 deque 中的元素原地 (in-place) 倒序排列並回傳 ``None``\\ 。" #: ../../library/collections.rst:568 msgid "" "Rotate the deque *n* steps to the right. If *n* is negative, rotate to the " "left." msgstr "將 deque 向右輪轉 *n* 步。若 *n* 為負值則向左輪轉。" #: ../../library/collections.rst:571 msgid "" "When the deque is not empty, rotating one step to the right is equivalent to " "``d.appendleft(d.pop())``, and rotating one step to the left is equivalent " "to ``d.append(d.popleft())``." msgstr "" "當 deque 不是空的,向右輪轉一步和 ``d.appendleft(d.pop())`` 有相同意義,而向" "左輪轉亦等價於 ``d.append(d.popleft())``\\ 。" #: ../../library/collections.rst:576 msgid "Deque objects also provide one read-only attribute:" msgstr "Deque 物件也提供了一個唯讀屬性:" #: ../../library/collections.rst:580 msgid "Maximum size of a deque or ``None`` if unbounded." msgstr "Deque 的最大長度,如果不限制長度的話則為 ``None``\\ 。" #: ../../library/collections.rst:585 msgid "" "In addition to the above, deques support iteration, pickling, ``len(d)``, " "``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing " "with the :keyword:`in` operator, and subscript references such as ``d[0]`` " "to access the first element. Indexed access is O(1) at both ends but slows " "to O(n) in the middle. For fast random access, use lists instead." msgstr "" "除了以上使用方式,deque 亦支援了疊代、pickle、``len(d)``、``reversed(d)``、" "``copy.copy(d)``、``copy.deepcopy(d)``、用 :keyword:`in` 運算子來作成員檢測以" "及像是 ``d[0]`` 的標號引用來取得第一個元素。在兩端做索引存取的複雜度為 O(1) " "但越靠近中間則減慢至 O(n)。若想要隨機而快速的存取,使用 list 會較為合適。" #: ../../library/collections.rst:591 msgid "" "Starting in version 3.5, deques support ``__add__()``, ``__mul__()``, and " "``__imul__()``." msgstr "" "自從 3.5 版本起,deque 開始支援 ``__add__()``、``__mul__()`` 和 " "``__imul__()``。" #: ../../library/collections.rst:594 msgid "Example:" msgstr "範例:" #: ../../library/collections.rst:651 msgid ":class:`deque` Recipes" msgstr ":class:`deque` 用法" #: ../../library/collections.rst:653 msgid "This section shows various approaches to working with deques." msgstr "這一章節提供了多種操作 deque 的案例。" #: ../../library/collections.rst:655 msgid "" "Bounded length deques provide functionality similar to the ``tail`` filter " "in Unix::" msgstr "" "被限制長度的 deque 功能類似 Unix 中的 ``tail`` filter:\n" "\n" "::" #: ../../library/collections.rst:663 msgid "" "Another approach to using deques is to maintain a sequence of recently added " "elements by appending to the right and popping to the left::" msgstr "" "另一用法是透過從右邊加入、從左邊移除來維護最近加入元素的 list:\n" "\n" "::" #: ../../library/collections.rst:678 msgid "" "A `round-robin scheduler `_ can be implemented with input iterators stored in a :" "class:`deque`. Values are yielded from the active iterator in position " "zero. If that iterator is exhausted, it can be removed with :meth:`~deque." "popleft`; otherwise, it can be cycled back to the end with the :meth:`~deque." "rotate` method::" msgstr "" "一個\\ `輪詢調度器 `_\\ 可以透過在 :class:`deque` 中放入 iterator 來實現,值自" "當前 iterator 的位置 0 取出,如果 iterator 已經消耗完畢就用 :meth:`~deque." "popleft` 將其從佇列中移除,否則利用 :meth:`~deque.rotate` 來將其移至佇列尾" "端:\n" "\n" "::" #: ../../library/collections.rst:697 msgid "" "The :meth:`~deque.rotate` method provides a way to implement :class:`deque` " "slicing and deletion. For example, a pure Python implementation of ``del " "d[n]`` relies on the ``rotate()`` method to position elements to be popped::" msgstr "" ":meth:`~deque.rotate` 提供了可以用來實作 :class:`deque` 切片和刪除的方法。舉" "例來說,用純 Python 實作 ``del d[n]`` 需要用 ``rotate()`` 來定位要被移除的元" "素:\n" "\n" "::" #: ../../library/collections.rst:706 msgid "" "To implement :class:`deque` slicing, use a similar approach applying :meth:" "`~deque.rotate` to bring a target element to the left side of the deque. " "Remove old entries with :meth:`~deque.popleft`, add new entries with :meth:" "`~deque.extend`, and then reverse the rotation. With minor variations on " "that approach, it is easy to implement Forth style stack manipulations such " "as ``dup``, ``drop``, ``swap``, ``over``, ``pick``, ``rot``, and ``roll``." msgstr "" "要實現 :class:`deque` 切片,可使用近似以下方法:使用 :meth:`~deque.rotate` 來" "將目標元素移動到 deque 最左側,用 :meth:`~deque.popleft` 移除舊元素並用 :" "meth:`~deque.extend` 加入新元素,最後再反向 rotate。在這個方法上做小小的更動" "就能簡單地實現 Forth 風格的 stack 操作,例如 ``dup``、``drop``、``swap``、" "``over``、``pick``、``rot`` 和 ``roll``。" #: ../../library/collections.rst:716 msgid ":class:`defaultdict` objects" msgstr ":class:`defaultdict` 物件" #: ../../library/collections.rst:720 msgid "" "Return a new dictionary-like object. :class:`defaultdict` is a subclass of " "the built-in :class:`dict` class. It overrides one method and adds one " "writable instance variable. The remaining functionality is the same as for " "the :class:`dict` class and is not documented here." msgstr "" "回傳一個新的類似字典的物件。\\ :class:`defaultdict` 是內建類別 :class:`dict` " "的子類別。它覆蓋掉了一個方法並添加了一個可寫入的實例變數。其餘功能與 :class:" "`dict` 相同,此文件不再複述。" #: ../../library/collections.rst:725 msgid "" "The first argument provides the initial value for the :attr:" "`default_factory` attribute; it defaults to ``None``. All remaining " "arguments are treated the same as if they were passed to the :class:`dict` " "constructor, including keyword arguments." msgstr "" "第一個引數為 :attr:`default_factory` 屬性提供了初始值,他被預設為 ``None``," "所有其他的引數(包括關鍵字引數)都會被傳遞給 :class:`dict` 的建構函式 " "(constructor)。" #: ../../library/collections.rst:731 msgid "" ":class:`defaultdict` objects support the following method in addition to the " "standard :class:`dict` operations:" msgstr ":class:`defaultdict` 物件支援以下 :class:`dict` 所沒有的方法:" #: ../../library/collections.rst:736 msgid "" "If the :attr:`default_factory` attribute is ``None``, this raises a :exc:" "`KeyError` exception with the *key* as argument." msgstr "" "如果 :attr:`default_factory` 屬性為 ``None``,呼叫此方法會引發一個附帶引數 " "*key* 的 :exc:`KeyError` 例外。" #: ../../library/collections.rst:739 msgid "" "If :attr:`default_factory` is not ``None``, it is called without arguments " "to provide a default value for the given *key*, this value is inserted in " "the dictionary for the *key*, and returned." msgstr "" "如果 :attr:`default_factory` 不為 ``None``,它會不帶引數地被呼叫來為給定的 " "*key* 提供一個預設值,這個值和 *key* 被作為鍵值對來插入到字典中,並且被此方法" "所回傳。" #: ../../library/collections.rst:743 msgid "" "If calling :attr:`default_factory` raises an exception this exception is " "propagated unchanged." msgstr "" "如果呼叫 :attr:`default_factory` 時發生例外,則該例外將會保持不變地向外傳遞。" #: ../../library/collections.rst:746 msgid "" "This method is called by the :meth:`__getitem__` method of the :class:`dict` " "class when the requested key is not found; whatever it returns or raises is " "then returned or raised by :meth:`__getitem__`." msgstr "" "在無法找到所要求的鍵時,此方法會被 :class:`dict` 類別的 :meth:`__getitem__` " "方法呼叫。無論此方法回傳了值還是引發了例外,都會被 :meth:`__getitem__` 所傳" "遞。" #: ../../library/collections.rst:750 msgid "" "Note that :meth:`__missing__` is *not* called for any operations besides :" "meth:`__getitem__`. This means that :meth:`get` will, like normal " "dictionaries, return ``None`` as a default rather than using :attr:" "`default_factory`." msgstr "" "注意,\\ :meth:`__missing__` *不會*\\ 被 :meth:`__getitem__` 以外的其他方法呼" "叫,這意味著 :meth:`get` 會像一般的 dict 那樣回傳 ``None`` 做為預設值,而非使" "用 :attr:`default_factory`。" #: ../../library/collections.rst:756 msgid ":class:`defaultdict` objects support the following instance variable:" msgstr ":class:`defaultdict` 物件支援以下實例變數:" #: ../../library/collections.rst:761 msgid "" "This attribute is used by the :meth:`__missing__` method; it is initialized " "from the first argument to the constructor, if present, or to ``None``, if " "absent." msgstr "" "此屬性為 :meth:`__missing__` 方法所使用。如果有引數被傳入建構函式,則此屬性會" "被初始化成第一個引數,如未提供引數則被初始化為 ``None``。" #: ../../library/collections.rst:765 ../../library/collections.rst:1182 msgid "" "Added merge (``|``) and update (``|=``) operators, specified in :pep:`584`." msgstr "新增合併 (``|``) 和更新 (``|=``) 運算子,請見 :pep:`584`。" #: ../../library/collections.rst:771 msgid ":class:`defaultdict` Examples" msgstr ":class:`defaultdict` 範例" #: ../../library/collections.rst:773 msgid "" "Using :class:`list` as the :attr:`~defaultdict.default_factory`, it is easy " "to group a sequence of key-value pairs into a dictionary of lists:" msgstr "" "使用 :class:`list` 作為 :attr:`~defaultdict.default_factory` 可以很輕鬆地將鍵" "值對序列轉換為包含 list 之字典:" #: ../../library/collections.rst:784 msgid "" "When each key is encountered for the first time, it is not already in the " "mapping; so an entry is automatically created using the :attr:`~defaultdict." "default_factory` function which returns an empty :class:`list`. The :meth:" "`list.append` operation then attaches the value to the new list. When keys " "are encountered again, the look-up proceeds normally (returning the list for " "that key) and the :meth:`list.append` operation adds another value to the " "list. This technique is simpler and faster than an equivalent technique " "using :meth:`dict.setdefault`:" msgstr "" "當每個鍵第一次被存取時,它還沒有存在於對映中,所以會自動呼叫 :attr:" "`~defaultdict.default_factory` 方法來回傳一個空的 :class:`list` 以建立一個條" "目,\\ :meth:`list.append` 操作後續會再新增值到這個新的列表裡。當再次存取該鍵" "時,就如普通字典般操作(回傳該鍵所對應到的 list),\\ :meth:`list.append` 也" "會新增另一個值到 list 中。和使用與其等價的 :meth:`dict.setdefault` 相比,這個" "技巧更加快速和簡單:" #: ../../library/collections.rst:799 msgid "" "Setting the :attr:`~defaultdict.default_factory` to :class:`int` makes the :" "class:`defaultdict` useful for counting (like a bag or multiset in other " "languages):" msgstr "" "設定 :attr:`~defaultdict.default_factory` 為 :class:`int` 使得 :class:" "`defaultdict` 可被用於計數(類似其他語言中的 bag 或 multiset):" #: ../../library/collections.rst:811 msgid "" "When a letter is first encountered, it is missing from the mapping, so the :" "attr:`~defaultdict.default_factory` function calls :func:`int` to supply a " "default count of zero. The increment operation then builds up the count for " "each letter." msgstr "" "當一個字母首次被存取時,它並不存在於對映中,則 :attr:`~defaultdict." "default_factory` 函式會呼叫 :func:`int` 來提供一個整數 0 作為預設值。後續的增" "加操作繼續對每個字母做計數。" #: ../../library/collections.rst:815 msgid "" "The function :func:`int` which always returns zero is just a special case of " "constant functions. A faster and more flexible way to create constant " "functions is to use a lambda function which can supply any constant value " "(not just zero):" msgstr "" "函式 :func:`int` 總是回傳 0,這是常數函式的特殊情況。一個更快、更有彈性的方法" "是使用 lambda 函式來提供任何常數值(不用一定要是 0):" #: ../../library/collections.rst:828 msgid "" "Setting the :attr:`~defaultdict.default_factory` to :class:`set` makes the :" "class:`defaultdict` useful for building a dictionary of sets:" msgstr "" "將 :attr:`~defaultdict.default_factory` 設為 :class:`set` 使 :class:" "`defaultdict` 可用於構建一個值為 set 的字典:" #: ../../library/collections.rst:841 msgid ":func:`namedtuple` Factory Function for Tuples with Named Fields" msgstr ":func:`namedtuple` 擁有具名欄位之 tuple 的工廠函式" #: ../../library/collections.rst:843 msgid "" "Named tuples assign meaning to each position in a tuple and allow for more " "readable, self-documenting code. They can be used wherever regular tuples " "are used, and they add the ability to access fields by name instead of " "position index." msgstr "" "Named tuple(具名元組)賦予 tuple 中各個位置意義,使程式碼更有可讀性與自我文" "件性。它們可以用於任何普通 tuple 可使用的場合,賦予其透過名稱(而非位置索引)" "來存取欄位的能力。" #: ../../library/collections.rst:849 msgid "" "Returns a new tuple subclass named *typename*. The new subclass is used to " "create tuple-like objects that have fields accessible by attribute lookup as " "well as being indexable and iterable. Instances of the subclass also have a " "helpful docstring (with typename and field_names) and a helpful :meth:" "`__repr__` method which lists the tuple contents in a ``name=value`` format." msgstr "" "回傳一個名為 *typename* 的新 tuple 子類別。這個新的子類別被用於建立類似 " "tuple 的物件,可以透過屬性名稱來存取欄位,它同時也是可索引 (indexable) 和可疊" "代的 (iterable)。子類別實例同樣有文件字串 (docstring)(有類別名 typename 和欄" "位名 field_names)和一個好用的 :meth:`__repr__` 方法,可將 tuple 內容以 " "``name=value`` 格式列出。" #: ../../library/collections.rst:855 msgid "" "The *field_names* are a sequence of strings such as ``['x', 'y']``. " "Alternatively, *field_names* can be a single string with each fieldname " "separated by whitespace and/or commas, for example ``'x y'`` or ``'x, y'``." msgstr "" "*field_names* 是一個像 ``['x', 'y']`` 一樣的字串序列。*field_names* 也可以是" "一個用空白或逗號分隔各個欄位名稱的字串,比如 ``'x y'`` 或者 ``'x, y'``。" #: ../../library/collections.rst:859 msgid "" "Any valid Python identifier may be used for a fieldname except for names " "starting with an underscore. Valid identifiers consist of letters, digits, " "and underscores but do not start with a digit or underscore and cannot be a :" "mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, or *raise*." msgstr "" "除了底線開頭以外的其他任何有效 Python 識別字 (identifier) 都可以作為欄位名" "稱,有效識別字由字母、數字、底線所組成,但不能是數字或底線開頭,也不能是關鍵" "詞 :mod:`keyword`,例如 *class*、*for*、*return*、*global*、*pass* 或 " "*raise*。" #: ../../library/collections.rst:865 msgid "" "If *rename* is true, invalid fieldnames are automatically replaced with " "positional names. For example, ``['abc', 'def', 'ghi', 'abc']`` is " "converted to ``['abc', '_1', 'ghi', '_3']``, eliminating the keyword ``def`` " "and the duplicate fieldname ``abc``." msgstr "" "如果 *rename* 為真值,無效的欄位名稱會自動被位置名稱取代。比如 ``['abc', " "'def', 'ghi', 'abc']`` 會被轉換成 ``['abc', '_1', 'ghi', '_3']``,移除了關鍵" "字 ``def`` 和重複欄位名 ``abc``。" #: ../../library/collections.rst:870 msgid "" "*defaults* can be ``None`` or an :term:`iterable` of default values. Since " "fields with a default value must come after any fields without a default, " "the *defaults* are applied to the rightmost parameters. For example, if the " "fieldnames are ``['x', 'y', 'z']`` and the defaults are ``(1, 2)``, then " "``x`` will be a required argument, ``y`` will default to ``1``, and ``z`` " "will default to ``2``." msgstr "" "*defaults* 可以為 ``None`` 或者是一個預設值的 :term:`iterable`。因為有預設值" "的欄位必須出現在那些沒有預設值的欄位之後,*defaults* 是被應用在右側的引數。例" "如 fieldnames 為 ``['x', 'y', 'z']`` 且 defaults 為 ``(1, 2)``,那麼 ``x`` 就" "必須被給定一個引數,``y`` 被預設為 ``1``,``z`` 則被預設為 ``2``。" #: ../../library/collections.rst:877 msgid "" "If *module* is defined, the ``__module__`` attribute of the named tuple is " "set to that value." msgstr "" "如果 *module* 值有被定義,named tuple 的 ``__module__`` 屬性就被設定為該值。" #: ../../library/collections.rst:880 msgid "" "Named tuple instances do not have per-instance dictionaries, so they are " "lightweight and require no more memory than regular tuples." msgstr "" "Named tuple 實例中沒有字典,所以它們更加輕量,且和一般 tuple 相比佔用更少記憶" "體。" #: ../../library/collections.rst:883 msgid "" "To support pickling, the named tuple class should be assigned to a variable " "that matches *typename*." msgstr "要支援 pickle,應將 named tuple 類別賦值給一個符合 *typename* 的變數。" #: ../../library/collections.rst:886 msgid "Added support for *rename*." msgstr "新增對於 *rename* 的支援。" #: ../../library/collections.rst:889 msgid "" "The *verbose* and *rename* parameters became :ref:`keyword-only arguments " "`." msgstr "" "*verbose* 和 *rename* 參數成為\\ :ref:`僅限關鍵字引數 `\\ 。" #: ../../library/collections.rst:893 msgid "Added the *module* parameter." msgstr "新增 *module* 參數。" #: ../../library/collections.rst:896 msgid "Removed the *verbose* parameter and the :attr:`_source` attribute." msgstr "移除 *verbose* 參數和 :attr:`_source` 屬性。" #: ../../library/collections.rst:899 msgid "" "Added the *defaults* parameter and the :attr:`_field_defaults` attribute." msgstr "新增 *defaults* 參數和 :attr:`_field_defaults` 屬性。" #: ../../library/collections.rst:919 msgid "" "Named tuples are especially useful for assigning field names to result " "tuples returned by the :mod:`csv` or :mod:`sqlite3` modules::" msgstr "" "Named tuple 在賦予欄位名稱於 :mod:`csv` 或 :mod:`sqlite3` 模組回傳之 tuple 時" "相當有用:\n" "\n" "::" #: ../../library/collections.rst:935 msgid "" "In addition to the methods inherited from tuples, named tuples support three " "additional methods and two attributes. To prevent conflicts with field " "names, the method and attribute names start with an underscore." msgstr "" "除了繼承自 tuple 的方法,named tuple 還支援三個額外的方法和兩個屬性。為了防止" "欄位名稱有衝突,方法和屬性的名稱以底線開頭。" #: ../../library/collections.rst:941 msgid "" "Class method that makes a new instance from an existing sequence or iterable." msgstr "從已存在的序列或可疊代物件建立一個新實例的類別方法。" #: ../../library/collections.rst:951 msgid "" "Return a new :class:`dict` which maps field names to their corresponding " "values:" msgstr "回傳一個將欄位名稱對映至對應值的 :class:`dict`:" #: ../../library/collections.rst:960 msgid "Returns an :class:`OrderedDict` instead of a regular :class:`dict`." msgstr "回傳一個 :class:`OrderedDict` 而非 :class:`dict`。" #: ../../library/collections.rst:963 msgid "" "Returns a regular :class:`dict` instead of an :class:`OrderedDict`. As of " "Python 3.7, regular dicts are guaranteed to be ordered. If the extra " "features of :class:`OrderedDict` are required, the suggested remediation is " "to cast the result to the desired type: ``OrderedDict(nt._asdict())``." msgstr "" "回傳一個常規 :class:`dict` 而非 :class:`OrderedDict`,自從 Python 3.7 開始," "dict 已經保證有順序性,如果需要 :class:`OrderedDict` 所專屬的特性,推薦的解法" "是將結果專換成所需的類型:\\ ``OrderedDict(nt._asdict())``\\ 。" #: ../../library/collections.rst:972 msgid "" "Return a new instance of the named tuple replacing specified fields with new " "values::" msgstr "" "回傳一個新的 named tuple 實例,並將指定欄位替換為新的值:\n" "\n" "::" #: ../../library/collections.rst:984 msgid "" "Tuple of strings listing the field names. Useful for introspection and for " "creating new named tuple types from existing named tuples." msgstr "" "列出 tuple 欄位名稱的字串,用於自我檢查或是從現有 named tuple 建立一個新的 " "named tuple 型別。" #: ../../library/collections.rst:999 msgid "Dictionary mapping field names to default values." msgstr "將欄位名稱對映至預設值的字典。" #: ../../library/collections.rst:1009 msgid "" "To retrieve a field whose name is stored in a string, use the :func:" "`getattr` function:" msgstr "要取得這個名稱存於字串的欄位,要使用 :func:`getattr` 函式:" #: ../../library/collections.rst:1015 msgid "" "To convert a dictionary to a named tuple, use the double-star-operator (as " "described in :ref:`tut-unpacking-arguments`):" msgstr "" "(如\\ :ref:`tut-unpacking-arguments`\\ 所述)將一個字典轉換成 named tuple," "要使用 \\*\\* 雙星號運算子:" #: ../../library/collections.rst:1022 msgid "" "Since a named tuple is a regular Python class, it is easy to add or change " "functionality with a subclass. Here is how to add a calculated field and a " "fixed-width print format:" msgstr "" "因為一個 named tuple 是一個常規的 Python 類別,我們可以很容易的透過子類別來新" "增或更改功能,以下是如何新增一個計算得到的欄位和固定寬度的輸出列印格式:" #: ../../library/collections.rst:1041 msgid "" "The subclass shown above sets ``__slots__`` to an empty tuple. This helps " "keep memory requirements low by preventing the creation of instance " "dictionaries." msgstr "" "上面的子類別將 ``__slots__`` 設定為空 tuple,這樣一來就防止了字典實例被建立," "因而保持了較低的記憶體用量。" #: ../../library/collections.rst:1044 msgid "" "Subclassing is not useful for adding new, stored fields. Instead, simply " "create a new named tuple type from the :attr:`~somenamedtuple._fields` " "attribute:" msgstr "" "子類別化無法用於增加新的、已被儲存的欄位,應當透過 :attr:`~somenamedtuple." "_fields` 屬性以建立一個新的 named tuple 來實現:" #: ../../library/collections.rst:1049 msgid "" "Docstrings can be customized by making direct assignments to the ``__doc__`` " "fields:" msgstr "透過直接賦值給 ``__doc__``,可以自訂說明文件字串:" #: ../../library/collections.rst:1058 msgid "Property docstrings became writeable." msgstr "文件字串屬性變成可寫入。" #: ../../library/collections.rst:1063 msgid "" "See :class:`typing.NamedTuple` for a way to add type hints for named " "tuples. It also provides an elegant notation using the :keyword:`class` " "keyword::" msgstr "" "關於為 named tuple 新增型別提示的方法,請參閱 :class:`typing.NamedTuple`,它" "運用 :keyword:`class` 關鍵字以提供了一個簡潔的表示法:\n" "\n" "::" #: ../../library/collections.rst:1072 msgid "" "See :meth:`types.SimpleNamespace` for a mutable namespace based on an " "underlying dictionary instead of a tuple." msgstr "" "關於以 dict 而非 tuple 為底層的可變命名空間,請參考 :meth:`types." "SimpleNamespace`。" #: ../../library/collections.rst:1075 msgid "" "The :mod:`dataclasses` module provides a decorator and functions for " "automatically adding generated special methods to user-defined classes." msgstr "" ":mod:`dataclasses` 模組提供了一個裝飾器和一些函式,用於自動將被生成的特殊方法" "新增到使用者定義的類別中。" #: ../../library/collections.rst:1080 msgid ":class:`OrderedDict` objects" msgstr ":class:`OrderedDict` 物件" #: ../../library/collections.rst:1082 msgid "" "Ordered dictionaries are just like regular dictionaries but have some extra " "capabilities relating to ordering operations. They have become less " "important now that the built-in :class:`dict` class gained the ability to " "remember insertion order (this new behavior became guaranteed in Python 3.7)." msgstr "" "Ordered dictionary(有序字典)就像常規字典一樣,但有一些與排序操作相關的額外" "功能,但由於內建的 :class:`dict` 類別現在已經有記憶插入順序的能力(Python " "3.7 中確保了這種新行為),它們變得不那麼重要了。" #: ../../library/collections.rst:1088 msgid "Some differences from :class:`dict` still remain:" msgstr "仍存在一些與 :class:`dict` 的不同之處:" #: ../../library/collections.rst:1090 msgid "" "The regular :class:`dict` was designed to be very good at mapping " "operations. Tracking insertion order was secondary." msgstr "" "常規的 :class:`dict` 被設計成非常擅長於對映相關操作,追蹤插入的順序為次要目" "標。" #: ../../library/collections.rst:1093 msgid "" "The :class:`OrderedDict` was designed to be good at reordering operations. " "Space efficiency, iteration speed, and the performance of update operations " "were secondary." msgstr "" ":class:`OrderedDict` 則被設計成擅長於重新排序相關的操作,空間效率、疊代速度和" "更新操作的效能則為次要設計目標。" #: ../../library/collections.rst:1097 msgid "" "The :class:`OrderedDict` algorithm can handle frequent reordering operations " "better than :class:`dict`. As shown in the recipes below, this makes it " "suitable for implementing various kinds of LRU caches." msgstr "" ":class:`OrderedDict` 比起 :class:`dict` 更適合處理頻繁的重新排序操作,如在下" "方用法中所示,這讓它適合用於多種 LRU cache 的實作中。" #: ../../library/collections.rst:1101 msgid "" "The equality operation for :class:`OrderedDict` checks for matching order." msgstr ":class:`OrderedDict` 之相等性運算會檢查順序是否相同。" #: ../../library/collections.rst:1103 msgid "" "A regular :class:`dict` can emulate the order sensitive equality test with " "``p == q and all(k1 == k2 for k1, k2 in zip(p, q))``." msgstr "" "一個一般的 :class:`dict` 可以用 ``p == q and all(k1 == k2 for k1, k2 in " "zip(p, q))`` 來效仿有檢查順序的相等性運算。" #: ../../library/collections.rst:1106 msgid "" "The :meth:`popitem` method of :class:`OrderedDict` has a different " "signature. It accepts an optional argument to specify which item is popped." msgstr "" ":class:`OrderedDict` 類別的 :meth:`popitem` 方法有不同的函式簽名 " "(signature),它接受傳入一個選擇性引數來指定要移除哪個元素。" #: ../../library/collections.rst:1109 msgid "" "A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=True)`` " "with ``d.popitem()`` which is guaranteed to pop the rightmost (last) item." msgstr "" "一個一般的 :class:`dict` 可以用 ``d.popitem()`` 來效仿 OrderedDict 的 ``od." "popitem(last=True)``\\ ,這保證會移除最右邊(最後一個)的元素。" #: ../../library/collections.rst:1112 msgid "" "A regular :class:`dict` can emulate OrderedDict's ``od.popitem(last=False)`` " "with ``(k := next(iter(d)), d.pop(k))`` which will return and remove the " "leftmost (first) item if it exists." msgstr "" "一個一般的 :class:`dict` 可以用 ``(k := next(iter(d)), d.pop(k))`` 來效仿 " "OrderedDict 的 ``od.popitem(last=False)``\\ ,若最左邊(第一個)的元素存在," "則將其回傳並移除。" #: ../../library/collections.rst:1116 msgid "" ":class:`OrderedDict` has a :meth:`move_to_end` method to efficiently " "reposition an element to an endpoint." msgstr "" ":class:`OrderedDict` 有個 :meth:`move_to_end` 方法可有效率地將一個元素重新排" "列到任一端。" #: ../../library/collections.rst:1119 msgid "" "A regular :class:`dict` can emulate OrderedDict's ``od.move_to_end(k, " "last=True)`` with ``d[k] = d.pop(k)`` which will move the key and its " "associated value to the rightmost (last) position." msgstr "" "一個一般的 :class:`dict` 可以用 ``d[k] = d.pop(k)`` 來效仿 OrderedDict 的 " "``od.move_to_end(k, last=True)``\\ ,這會將該鍵與其對應到的值移動至最右(最後" "面)的位置。" #: ../../library/collections.rst:1123 msgid "" "A regular :class:`dict` does not have an efficient equivalent for " "OrderedDict's ``od.move_to_end(k, last=False)`` which moves the key and its " "associated value to the leftmost (first) position." msgstr "" "一個一般的 :class:`dict` 沒有和 OrderedDict 的 ``od.move_to_end(k, " "last=False)`` 等價的有效方式,這是將鍵與其對應到的值移動至最左(最前面)位置" "的方法。" #: ../../library/collections.rst:1127 msgid "Until Python 3.8, :class:`dict` lacked a :meth:`__reversed__` method." msgstr "在 Python 3.8 之前,:class:`dict` 並沒有 :meth:`__reversed__` 方法。" #: ../../library/collections.rst:1132 msgid "" "Return an instance of a :class:`dict` subclass that has methods specialized " "for rearranging dictionary order." msgstr "" "回傳一個 :class:`dict` 子類別的實例,它具有專門用於重新排列字典順序的方法。" #: ../../library/collections.rst:1139 msgid "" "The :meth:`popitem` method for ordered dictionaries returns and removes a " "(key, value) pair. The pairs are returned in :abbr:`LIFO (last-in, first-" "out)` order if *last* is true or :abbr:`FIFO (first-in, first-out)` order if " "false." msgstr "" "Ordered dictionary 的 :meth:`popitem` 方法移除並回傳一個鍵值 (key, value) " "對。如果 *last* 為真值,則按 :abbr:`LIFO (last-in, first-out)` 後進先出的順序" "回傳鍵值對,否則就按 :abbr:`FIFO (first-in, first-out)` 先進先出的順序回傳鍵" "值對。" #: ../../library/collections.rst:1146 msgid "" "Move an existing *key* to either end of an ordered dictionary. The item is " "moved to the right end if *last* is true (the default) or to the beginning " "if *last* is false. Raises :exc:`KeyError` if the *key* does not exist:" msgstr "" "將現有的 *key* 移動到 ordered dictionary 的任一端。如果 *last* 為真值(此為預" "設值)則將元素移至右端;如果 *last* 為假值則將元素移至左端。如果 *key* 不存在" "則會引發 :exc:`KeyError`:" #: ../../library/collections.rst:1163 msgid "" "In addition to the usual mapping methods, ordered dictionaries also support " "reverse iteration using :func:`reversed`." msgstr "" "除了普通的對映方法,ordered dictionary 還支援了透過 :func:`reversed` 來做倒序" "疊代。" #: ../../library/collections.rst:1166 msgid "" "Equality tests between :class:`OrderedDict` objects are order-sensitive and " "are implemented as ``list(od1.items())==list(od2.items())``. Equality tests " "between :class:`OrderedDict` objects and other :class:`~collections.abc." "Mapping` objects are order-insensitive like regular dictionaries. This " "allows :class:`OrderedDict` objects to be substituted anywhere a regular " "dictionary is used." msgstr "" ":class:`OrderedDict` 物件之間的相等性運算是會檢查順序是否相同的,是透過 " "``list(od1.items())==list(od2.items())`` 來實現。\\ :class:`OrderedDict` 物件" "和其他 :class:`~collections.abc.Mapping` 物件間的相等性運算則像普通字典一樣不" "考慮順序性,這使得 :class:`OrderedDict` 可於任何字典可使用的時機中被替換掉。" #: ../../library/collections.rst:1173 msgid "" "The items, keys, and values :term:`views ` of :class:" "`OrderedDict` now support reverse iteration using :func:`reversed`." msgstr "" ":class:`OrderedDict` 的項 (item)、鍵與值之\\ :term:`視圖 `\\ 現在可透過 :func:`reversed` 來倒序疊代。" #: ../../library/collections.rst:1177 msgid "" "With the acceptance of :pep:`468`, order is retained for keyword arguments " "passed to the :class:`OrderedDict` constructor and its :meth:`update` method." msgstr "" "隨著 :pep:`468` 被核可,被傳入給 :class:`OrderedDict` 建構函式與其 :meth:" "`update` 方法的關鍵字引數之順序被保留了下來。" #: ../../library/collections.rst:1187 msgid ":class:`OrderedDict` Examples and Recipes" msgstr ":class:`OrderedDict` 範例與用法" #: ../../library/collections.rst:1189 msgid "" "It is straightforward to create an ordered dictionary variant that remembers " "the order the keys were *last* inserted. If a new entry overwrites an " "existing entry, the original insertion position is changed and moved to the " "end::" msgstr "" "建立一個能夠記住鍵\\ *最後*\\ 插入順序的 ordered dictionary 變體很簡單。如果" "新條目覆蓋了現有條目,則原本插入位置會被更改並移動至末端:\n" "\n" "::" #: ../../library/collections.rst:1201 msgid "" "An :class:`OrderedDict` would also be useful for implementing variants of :" "func:`functools.lru_cache`:" msgstr "" ":class:`OrderedDict` 在實現一個 :func:`functools.lru_cache` 的變形版本時也非" "常有用:" #: ../../library/collections.rst:1300 msgid ":class:`UserDict` objects" msgstr ":class:`UserDict` 物件" #: ../../library/collections.rst:1302 msgid "" "The class, :class:`UserDict` acts as a wrapper around dictionary objects. " "The need for this class has been partially supplanted by the ability to " "subclass directly from :class:`dict`; however, this class can be easier to " "work with because the underlying dictionary is accessible as an attribute." msgstr "" ":class:`UserDict` 類別是作為 dict 物件的包裝器。因為已經可以直接自 :class:" "`dict` 建立子類別,這個類別的需求已部分被滿足,不過這個類別使用起來更方便,因" "為被包裝的字典可以作為其屬性來存取。" #: ../../library/collections.rst:1310 msgid "" "Class that simulates a dictionary. The instance's contents are kept in a " "regular dictionary, which is accessible via the :attr:`data` attribute of :" "class:`UserDict` instances. If *initialdata* is provided, :attr:`data` is " "initialized with its contents; note that a reference to *initialdata* will " "not be kept, allowing it to be used for other purposes." msgstr "" "模擬字典的類別。實例的內容被存於一個字典,可透過 :class:`UserDict` 的 :attr:" "`data` 屬性來做存取。如果有提供 *initialdata*\\ ,\\ :attr:`data` 屬性會被初" "始化為其值;要注意指到 *initialdata* 的參照不會被保留,使其可被用於其他目的。" #: ../../library/collections.rst:1316 msgid "" "In addition to supporting the methods and operations of mappings, :class:" "`UserDict` instances provide the following attribute:" msgstr "" "除了支援作為對映所需的方法與操作,\\ :class:`UserDict` 實例提供了以下屬性:" #: ../../library/collections.rst:1321 msgid "" "A real dictionary used to store the contents of the :class:`UserDict` class." msgstr "一個真實的字典,用於儲存 :class:`UserDict` 類別的資料內容。" #: ../../library/collections.rst:1327 msgid ":class:`UserList` objects" msgstr ":class:`UserList` 物件" #: ../../library/collections.rst:1329 msgid "" "This class acts as a wrapper around list objects. It is a useful base class " "for your own list-like classes which can inherit from them and override " "existing methods or add new ones. In this way, one can add new behaviors to " "lists." msgstr "" "此類別是 list 物件的包裝器。它是個方便的基礎類別,可繼承它並覆寫現有方法或加" "入新方法來定義你所需的一個類似於 list 的類別。如此一來,我們可以為 list 加入" "新的特性。" #: ../../library/collections.rst:1334 msgid "" "The need for this class has been partially supplanted by the ability to " "subclass directly from :class:`list`; however, this class can be easier to " "work with because the underlying list is accessible as an attribute." msgstr "" "因為已經可以直接自 :class:`list` 建立子類別,這個類別的需求已部分被滿足,不過" "這個類別使用起來更方便,因為被包裝的 list 可以作為其屬性來存取。" #: ../../library/collections.rst:1340 msgid "" "Class that simulates a list. The instance's contents are kept in a regular " "list, which is accessible via the :attr:`data` attribute of :class:" "`UserList` instances. The instance's contents are initially set to a copy " "of *list*, defaulting to the empty list ``[]``. *list* can be any iterable, " "for example a real Python list or a :class:`UserList` object." msgstr "" "模擬 list 的類別。實例的內容被存於一個 list,可透過 :class:`UserList` 的 :" "attr:`data` 屬性來做存取。實例內容被初始化為 *list* 的複製,預設為一個空的 " "list ``[]``。\\ *list* 可以是任何 iterable,例如一個真實的 Python list 或是一" "個 :class:`UserList` 物件。" #: ../../library/collections.rst:1346 msgid "" "In addition to supporting the methods and operations of mutable sequences, :" "class:`UserList` instances provide the following attribute:" msgstr "" "除了支援可變序列的方法與操作,\\ :class:`UserList` 實例提供了以下屬性:" #: ../../library/collections.rst:1351 msgid "" "A real :class:`list` object used to store the contents of the :class:" "`UserList` class." msgstr "" "一個真實的 :class:`list` 物件,用於儲存 :class:`UserList` 類別的資料內容。" #: ../../library/collections.rst:1354 msgid "" "**Subclassing requirements:** Subclasses of :class:`UserList` are expected " "to offer a constructor which can be called with either no arguments or one " "argument. List operations which return a new sequence attempt to create an " "instance of the actual implementation class. To do so, it assumes that the " "constructor can be called with a single parameter, which is a sequence " "object used as a data source." msgstr "" "**子類別化的條件:**\\ :class:`UserList` 的子類別應該要提供一個不需要引數或一" "個引數的建構函式。回傳一個新序列的 list 操作會從那些實作出來的類別建立一個實" "例,為了達成上述目的,它假設建構函式可傳入單一參數來呼叫,該參數即是做為數據" "來源的一個序列物件。" #: ../../library/collections.rst:1361 msgid "" "If a derived class does not wish to comply with this requirement, all of the " "special methods supported by this class will need to be overridden; please " "consult the sources for information about the methods which need to be " "provided in that case." msgstr "" "如果希望一個自此獲得的子類別不遵從上述要求,那所有該類別支援的特殊方法則必須" "被覆寫;請參考原始碼來理解在這情況下哪些方法是必須提供的。" #: ../../library/collections.rst:1367 msgid ":class:`UserString` objects" msgstr ":class:`UserString` 物件" #: ../../library/collections.rst:1369 msgid "" "The class, :class:`UserString` acts as a wrapper around string objects. The " "need for this class has been partially supplanted by the ability to subclass " "directly from :class:`str`; however, this class can be easier to work with " "because the underlying string is accessible as an attribute." msgstr "" ":class:`UserString` 類別是字串物件的包裝器,因為已經可以從 :class:`str` 直接" "建立子類別,這個類別的需求已經部分被滿足,不過這個類別使用起來更方便,因為被" "包裝的字串可以作為其屬性來存取。" #: ../../library/collections.rst:1377 msgid "" "Class that simulates a string object. The instance's content is kept in a " "regular string object, which is accessible via the :attr:`data` attribute " "of :class:`UserString` instances. The instance's contents are initially set " "to a copy of *seq*. The *seq* argument can be any object which can be " "converted into a string using the built-in :func:`str` function." msgstr "" "模擬字串物件的類別。實例的內容被存於一個字串物件,可透過 :class:`UserString` " "的 :attr:`data` 屬性來做存取。實例內容被初始化為 *seq* 的複製,\\ *seq* 引數" "可以是任何可被內建函式 :func:`str` 轉換成字串的物件。" #: ../../library/collections.rst:1384 msgid "" "In addition to supporting the methods and operations of strings, :class:" "`UserString` instances provide the following attribute:" msgstr "" "除了支援字串的方法和操作以外,\\ :class:`UserString` 實例也提供了以下屬性:" #: ../../library/collections.rst:1389 msgid "" "A real :class:`str` object used to store the contents of the :class:" "`UserString` class." msgstr "" "一個真實的 :class:`str` 物件,用來儲存 :class:`UserString` 類別的資料內容。" #: ../../library/collections.rst:1392 msgid "" "New methods ``__getnewargs__``, ``__rmod__``, ``casefold``, ``format_map``, " "``isprintable``, and ``maketrans``." msgstr "" "新增方法 ``__getnewargs__``、``__rmod__``、``casefold``、``format_map``、" "``isprintable`` 以及 ``maketrans``\\ 。"