collectionsContainer datatypes容器数据类型

Source code: Lib/collections/__init__.py


This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.该模块实现专门的容器数据类型,提供Python通用内置容器,dictlistsettuple的替代品。

namedtuple()

factory function for creating tuple subclasses with named fields用于创建具有命名字段的元组子类的工厂函数

deque

list-like container with fast appends and pops on either end列表式容器,两端都有快速的附件和弹出窗口

ChainMap

dict-like class for creating a single view of multiple mappings用于创建多个映射的单个视图的类dict

Counter

dict subclass for counting hashable objects用于计算哈希对象的dict子类

OrderedDict

dict subclass that remembers the order entries were added添加了记住订单条目的dict子类

defaultdict

dict subclass that calls a factory function to supply missing valuesdict子类,调用工厂函数以提供缺少的值

UserDict

wrapper around dictionary objects for easier dict subclassing围绕字典对象进行包装,以简化dict子类化

UserList

wrapper around list objects for easier list subclassing围绕列表对象进行包装,以简化列表子类化

UserString

wrapper around string objects for easier string subclassing围绕字符串对象进行包装,以简化字符串子类化

ChainMap objects对象

New in version 3.3.版本3.3中新增。

A ChainMap class is provided for quickly linking a number of mappings so they can be treated as a single unit. 提供了一个ChainMap类,用于快速链接多个映射,以便将它们视为单个单元。It is often much faster than creating a new dictionary and running multiple update() calls.它通常比创建新字典和运行多个update()调用快得多。

The class can be used to simulate nested scopes and is useful in templating.该类可用于模拟嵌套作用域,并在模板制作中很有用。

classcollections.ChainMap(*maps)

A ChainMap groups multiple dicts or other mappings together to create a single, updateable view. ChainMap将多个字典或其他映射组合在一起,以创建一个可更新的视图。If no maps are specified, a single empty dictionary is provided so that a new chain always has at least one mapping.如果没有指定maps,则提供一个空字典,以便新链始终至少有一个映射。

The underlying mappings are stored in a list. 底层映射存储在列表中。That list is public and can be accessed or updated using the maps attribute. 该列表是公共的,可以使用maps属性访问或更新。There is no other state.没有其他州。

Lookups search the underlying mappings successively until a key is found. 查找连续搜索底层映射,直到找到键。In contrast, writes, updates, and deletions only operate on the first mapping.相反,写入、更新和删除仅在第一个映射上操作。

A ChainMap incorporates the underlying mappings by reference. ChainMap通过引用合并了底层映射。So, if one of the underlying mappings gets updated, those changes will be reflected in ChainMap.因此,如果其中一个底层映射得到更新,这些更改将反映在ChainMap中。

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:此外,还有一个maps属性、一种创建新子文本的方法和一个用于访问除第一个映射之外的所有映射的属性:

maps

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.列表应始终包含至少一个映射。

new_child(m=None, **kwargs)

Returns a new ChainMap containing a new map followed by all of the maps in the current instance. 返回一个新的ChainMap,其中包含一个新映射,后跟当前实例中的所有映射。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). 如果指定m,它将成为映射列表前面的新映射;如果未指定,则使用空字典,因此对d.new_child()的调用等效于:ChainMap({}, *d.maps)If any keyword arguments are specified, they update passed map or new empty dict. 如果指定了任何关键字参数,它们将更新传递的映射或新的空dict。This method is used for creating subcontexts that can be updated without altering values in any of the parent mappings.此方法用于创建可以在不改变任何父映射中的值的情况下更新的子文本。

Changed in version 3.4:版本3.4中更改: The optional m parameter was added.添加了可选的m参数。

Changed in version 3.10:版本3.10中更改: Keyword arguments support was added.添加了关键字参数支持。

parents

Property returning a new ChainMap containing all of the maps in the current instance except the first one. 属性返回一个新的ChainMap,该链映射包含当前实例中除第一个映射外的所有映射。This is useful for skipping the first map in the search. 这对于跳过搜索中的第一个映射很有用。Use cases are similar to those for the nonlocal keyword used in nested scopes. 用例与嵌套作用域中使用的nonlocal关键字的用例类似。The use cases also parallel those for the built-in super() function. 这些用例还与内置super()函数的用例并行。A reference to d.parents is equivalent to:ChainMap(*d.maps[1:]).d.parents的引用相当于:ChainMap(*d.maps[1:])

Note, the iteration order of a ChainMap() is determined by scanning the mappings last to first:注意,ChainMap()的迭代顺序是通过从上到下扫描映射来确定的:

>>> baseline = {'music': 'bach', 'art': 'rembrandt'}
>>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}
>>> list(ChainMap(adjustments, baseline))
['music', 'art', 'opera']

This gives the same ordering as a series of dict.update() calls starting with the last mapping:这与从最后一个映射开始的一系列dict.update()调用的顺序相同:

>>> combined = baseline.copy()
>>> combined.update(adjustments)
>>> list(combined)
['music', 'art', 'opera']

Changed in version 3.9:版本3.9中更改: Added support for | and |= operators, specified in PEP 584.增加了对PEP 584中指定的||=运算符的支持。

See also

ChainMap Examples and Recipes示例和配方

This section shows various approaches to working with chained maps.本节介绍了使用链式地图的各种方法。

Example of simulating Python’s internal lookup chain:模拟Python内部查找链的示例:

import builtins
pylookup = ChainMap(locals(), globals(), vars(builtins))

Example of letting user specified command-line arguments take precedence over environment variables which in turn take precedence over default values:让用户指定的命令行参数优先于环境变量的示例,环境变量反过来优先于默认值:

import os, argparse
defaults = {'color': 'red', 'user': 'guest'}

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args()
command_line_args = {k: v for k, v in vars(namespace).items() if v is not None}

combined = ChainMap(command_line_args, os.environ, defaults)
print(combined['color'])
print(combined['user'])

Example patterns for using the ChainMap class to simulate nested contexts:使用ChainMap类模拟嵌套上下文的模式示例:

c = ChainMap()        # Create root context
d = c.new_child() # Create nested child context
e = c.new_child() # Child of c, independent from d
e.maps[0] # Current context dictionary -- like Python's locals()
e.maps[-1] # Root context -- like Python's globals()
e.parents # Enclosing context chain -- like Python's nonlocals
d['x'] = 1 # Set value in current context
d['x'] # Get first key in the chain of contexts
del d['x'] # Delete from current context
list(d) # All nested values
k in d # Check all nested values
len(d) # Number of nested values
d.items() # All nested items
dict(d) # Flatten into a regular dictionary

The ChainMap class only makes updates (writes and deletions) to the first mapping in the chain while lookups will search the full chain. ChainMap类仅对链中的第一个映射进行更新(写入和删除),而查找将搜索整个链。However, if deep writes and deletions are desired, it is easy to make a subclass that updates keys found deeper in the chain:然而,如果需要深度写入和删除,很容易生成一个子类来更新链中较深的键:

class DeepChainMap(ChainMap):
'Variant of ChainMap that allows direct updates to inner scopes'
def __setitem__(self, key, value):
for mapping in self.maps:
if key in mapping:
mapping[key] = value
return
self.maps[0][key] = value

def __delitem__(self, key):
for mapping in self.maps:
if key in mapping:
del mapping[key]
return
raise KeyError(key)

>>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'})
>>> d['lion'] = 'orange' # update an existing key two levels down
>>> d['snake'] = 'red' # new keys get added to the topmost dict
>>> del d['elephant'] # remove an existing key one level down
>>> d # display result
DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})

Counter objects对象

A counter tool is provided to support convenient and rapid tallies. 提供计数器工具以支持方便快速的计数。For example:例如:

>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
classcollections.Counter([iterable-or-mapping])

A Counter is a dict subclass for counting hashable objects. Counter是用于计算散列对象的dict子类。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 Counter class is similar to bags or multisets in other languages.Counter类类似于其他语言中的bags或Multiset。

Elements are counted from an iterable or initialized from another mapping (or counter):元素从iterable计数或从另一个mapping(或计数器)初始化:

>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args

Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a KeyError:计数器对象有一个字典接口,除了它们为缺失项返回零计数,而不是引发KeyError

>>> c = Counter(['eggs', 'ham'])
>>> c['bacon'] # count of a missing element is zero
0

Setting a count to zero does not remove an element from a counter. 将计数设置为零不会从计数器中删除元素。Use del to remove it entirely:使用del将其完全删除:

>>> c['sausage'] = 0                        # counter entry with a zero count
>>> del c['sausage'] # del actually removes the entry

New in version 3.1.版本3.1中新增。

Changed in version 3.7:版本3.7中更改: As a dict subclass, Counter inherited the capability to remember insertion order. 作为dict子类,Counter继承了记住插入顺序的能力。Math operations on Counter objects also preserve order. Counter对象上的数学运算也保持顺序。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.结果的顺序取决于元素在左操作数中第一次遇到的时间,然后是在右操作数中遇到的顺序。

Counter objects support additional methods beyond those available for all dictionaries:计数器对象支持除所有字典可用的方法之外的其他方法:

elements()

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, elements() will ignore it.如果元素的计数小于1,elements()将忽略它。

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
most_common([n])

Return a list of the n most common elements and their counts from the most common to the least. 返回n个最常见元素及其计数的列表,从最常见到最少。If n is omitted or None, most_common() returns all elements in the counter. 如果省略n或为Nonemost_common()将返回计数器中的所有元素。Elements with equal counts are ordered in the order first encountered:计数相等的元素按第一次遇到的顺序排序:

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
subtract([iterable-or-mapping])

Elements are subtracted from an iterable or from another mapping (or counter). 元素从iterable或另一个mapping(或计数器)中减去。Like dict.update() but subtracts counts instead of replacing them. dict.update()类似,但减去计数而不是替换计数。Both inputs and outputs may be zero or negative.输入和输出都可以为零或负。

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

New in version 3.2.版本3.2中新增。

total()

Compute the sum of the counts.计算计数之和。

>>> c = Counter(a=10, b=5, c=0)
>>> c.total()
15

New in version 3.10.版本3.10中新增。

The usual dictionary methods are available for Counter objects except for two which work differently for counters.通常的字典方法可用于Counter对象,但两种方法对计数器的工作方式不同。

fromkeys(iterable)

This class method is not implemented for Counter objects.该类方法不适用于Counter对象。

update([iterable-or-mapping])

Elements are counted from an iterable or added-in from another mapping (or counter). 元素从iterable计数或从另一个mapping(或计数器)添加。Like dict.update() but adds counts instead of replacing them. dict.update()类似,但添加计数而不是替换计数。Also, the iterable is expected to be a sequence of elements, not a sequence of (key, value) pairs.此外,iterable应该是元素序列,而不是(key, value)对序列。

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.所有这些测试都将缺少的元素视为具有零计数,以便Counter(a=1) == Counter(a=1, b=0)返回true

New in version 3.10.版本3.10中新增。Rich comparison operations were added.添加了丰富的比较操作。

Changed in version 3.10:版本3.10中更改: In equality tests, missing elements are treated as having zero counts. 在等式测试中,缺失元素被视为具有零计数。Formerly, Counter(a=3) and Counter(a=3, b=0) were considered distinct.以前,Counter(a=3)Counter(a=3, b=0)被认为是不同的。

Common patterns for working with Counter objects:使用Counter对象的常见模式:

c.total()                       # total of all counts
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
dict(c) # convert to a regular dictionary
c.items() # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1] # n least common elements
+c # remove zero and negative counts

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). 提供了几种数学运算,用于组合Counter对象以生成多集(计数大于零的计数器)。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.每个操作都可以接受有符号计数的输入,但输出将排除计数为零或更少的结果。

>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d # add two counters together: c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d # subtract (keeping only positive counts)
Counter({'a': 2})
>>> c & d # intersection: min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d # union: max(c[x], d[x])
Counter({'a': 3, 'b': 2})
>>> c == d # equality: c[x] == d[x]
False
>>> c <= d # inclusion: c[x] <= d[x]
False

Unary addition and subtraction are shortcuts for adding an empty counter or subtracting from an empty counter.一元加法和减法是添加空计数器或从空计数器中减法的快捷方式。

>>> c = Counter(a=2, b=-4)
>>> +c
Counter({'a': 2})
>>> -c
Counter({'b': 4})

New in version 3.3.版本3.3中新增。Added support for unary plus, unary minus, and in-place multiset operations.增加了对一元加、一元减和就地多集操作的支持。

Note

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.为了帮助处理这些用例,本节记录了最小范围和类型限制。

  • The Counter class itself is a dictionary subclass with no restrictions on its keys and values. Counter类本身是一个字典子类,对其键和值没有限制。The values are intended to be numbers representing counts, but you could store anything in the value field.这些值是表示计数的数字,但您可以在值字段中存储任何内容。

  • The most_common() method requires only that the values be orderable.most_common()方法只要求值可以排序。

  • For in-place operations such as c[key] += 1, the value type need only support addition and subtraction. 对于c[key] += 1之类的就地操作,值类型只需要支持加法和减法。So fractions, floats, and decimals would work and negative values are supported. 因此分数、浮点数和小数可以工作,并且支持负值。The same is also true for update() and subtract() which allow negative and zero values for both inputs and outputs.update()subtract()也是如此,它们允许输入和输出为负值和零值。

  • 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.没有类型限制,但值类型需要支持加法、减法和比较。

  • The elements() method requires integer counts. elements()方法需要整数计数。It ignores zero and negative counts.它忽略零计数和负计数。

See also另请参见

  • Bag class in Smalltalk.

  • Wikipedia entry for Multisets.Multisets的维基百科条目。

  • C++ multisets tutorial with examples.

  • 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.有关多集的数学运算及其用例,请参阅Knuth,Donald编写的《计算机编程艺术 第二卷》,第4.6.3节,练习19。

  • To enumerate all distinct multisets of a given size over a given set of elements, see itertools.combinations_with_replacement():要枚举给定元素集上给定大小的所有不同多集,请参阅itertools.combinations_with_replacement()

    map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC

deque objects对象

classcollections.deque([iterable[, maxlen]])

Returns a new deque object initialized left-to-right (using append()) with data from iterable. 使用可迭代对象中的数据从左到右(使用append())返回初始化的新队列对象。If iterable is not specified, the new deque is empty.如果未指定iterable,则新deque为空。

Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). 队列是堆栈和队列的泛化(名称发音为“deck”,是“双头队列”的缩写)。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.deque支持线程安全、内存高效的附加和弹出,在deque的任意一侧,在任意方向上的O(1)性能大致相同。

Though 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.虽然list对象支持类似的操作,但它们针对快速固定长度操作进行了优化,并为pop(0)insert(0, v)操作带来了O(n)内存移动成本,这会改变底层数据表示的大小和位置。

If maxlen is not specified or is None, deques may grow to an arbitrary length. 如果未指定maxlen或指定为None,则队列可能会增长到任意长度。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. 一旦有界长度deque已满,当添加新项时,从另一端丢弃相应数量的项。Bounded length deques provide functionality similar to the tail filter in Unix. 有界长度队列提供了类似于Unix中tail筛选器的功能。They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.它们还可用于跟踪只有最新活动才感兴趣的交易和其他数据池。

Deque objects support the following methods:deque对象支持以下方法:

append(x)

Add x to the right side of the deque.x添加到deque的右侧。

appendleft(x)

Add x to the left side of the deque.x添加到三角形的左侧。

clear()

Remove all elements from the deque leaving it with length 0.deque中删除所有元素,使其长度为0。

copy()

Create a shallow copy of the deque.创建deque的浅副本。

New in version 3.5.版本3.5中新增。

count(x)

Count the number of deque elements equal to x.计算等于xdeque元素数。

New in version 3.2.版本3.2中新增。

extend(iterable)

Extend the right side of the deque by appending elements from the iterable argument.通过附加iterable参数中的元素来扩展deque的右侧。

extendleft(iterable)

Extend the left side of the deque by appending elements from iterable. 通过附加iterable中的元素来扩展deque的左侧。Note, the series of left appends results in reversing the order of elements in the iterable argument.注意,一系列左附录会反转可迭代参数中元素的顺序。

index(x[, start[, stop]])

Return the position of x in the deque (at or after index start and before index stop). 返回xdeque中的位置(索引start之后或索引stop之前)。Returns the first match or raises ValueError if not found.返回第一个匹配项,如果未找到,则引发ValueError

New in version 3.5.版本3.5中新增。

insert(i, x)

Insert x into the deque at position i.x插入位置i处的三角形中。

If the insertion would cause a bounded deque to grow beyond maxlen, an IndexError is raised.如果插入会导致有界deque增长超过maxlen,则会引发IndexError

New in version 3.5.版本3.5中新增。

pop()

Remove and return an element from the right side of the deque. 从deque的右侧移除并返回一个元素。If no elements are present, raises an IndexError.如果不存在任何元素,则引发IndexError

popleft()

Remove and return an element from the left side of the deque. 从deque的左侧移除并返回一个元素。If no elements are present, raises an IndexError.如果不存在任何元素,则引发IndexError

remove(value)

Remove the first occurrence of value. 删除第一个出现的valueIf not found, raises a ValueError.如果未找到,则引发ValueError

reverse()

Reverse the elements of the deque in-place and then return None.deque的元素原地反转,然后返回None

New in version 3.2.版本3.2中新增。

rotate(n=1)

Rotate the deque n steps to the right. deque向右旋转n步。If n is negative, rotate to the left.如果n为负,则向左旋转。

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()).deque不为空时,向右旋转一步相当于d.appendleft(d.pop()),向左旋转一步相当于d.append(d.popleft())

Deque objects also provide one read-only attribute:deque对象还提供一个只读属性:

maxlen

Maximum size of a deque or None if unbounded.deque的最大大小,如果没有边界,则为None

New in version 3.1.版本3.1中新增。

In addition to the above, deques support iteration, pickling, len(d), reversed(d), copy.copy(d), copy.deepcopy(d), membership testing with the in operator, and subscript references such as d[0] to access the first element. 除上述内容外,queue还支持迭代、pickling、len(d)reversed(d)copy.copy(d)copy.deepcopy(d)、使用in运算符的成员身份测试以及诸如d[0]之类的下标引用来访问第一个元素。Indexed access is O(1) at both ends but slows to O(n) in the middle. 索引访问在两端为O(1),但在中间为O(n)。For fast random access, use lists instead.为了快速随机访问,请使用列表。

Starting in version 3.5, deques support __add__(), __mul__(), and __imul__().从3.5版开始,deque支持__add__()__mul__()__imul__()

Example:例子:

>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> for elem in d: # iterate over the deque's elements
... print(elem.upper())
G
H
I
>>> d.append('j') # add a new entry to the right side
>>> d.appendleft('f') # add a new entry to the left side
>>> d # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])

>>> d.pop() # return and remove the rightmost item
'j'
>>> d.popleft() # return and remove the leftmost item
'f'
>>> list(d) # list the contents of the deque
['g', 'h', 'i']
>>> d[0] # peek at leftmost item
'g'
>>> d[-1] # peek at rightmost item
'i'

>>> list(reversed(d)) # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d # search the deque
True
>>> d.extend('jkl') # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1) # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1) # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

>>> deque(reversed(d)) # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear() # empty the deque
>>> d.pop() # cannot pop from an empty deque
Traceback (most recent call last):
File "<pyshell#6>", line 1, in -toplevel-
d.pop()
IndexError: pop from an empty deque

>>> d.extendleft('abc') # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])

deque Recipes菜谱

This section shows various approaches to working with deques.本节展示了使用deque的各种方法。

Bounded length deques provide functionality similar to the tail filter in Unix:有界长度deque提供了类似于Unix中tail筛选器的功能:

def tail(filename, n=10):
'Return the last n lines of a file'
with open(filename) as f:
return deque(f, n)

Another approach to using deques is to maintain a sequence of recently added elements by appending to the right and popping to the left:使用deques的另一种方法是通过向右追加并向左弹出来维护最近添加的元素的序列:

def moving_average(iterable, n=3):
# moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
# http://en.wikipedia.org/wiki/Moving_average
it = iter(iterable)
d = deque(itertools.islice(it, n-1))
d.appendleft(0)
s = sum(d)
for elem in it:
s += elem - d.popleft()
d.append(elem)
yield s / n

A round-robin scheduler can be implemented with input iterators stored in a deque. 循环调度程序可以使用存储在deque中的输入迭代器来实现。Values are yielded from the active iterator in position zero. 从零位的活动迭代器中生成值。If that iterator is exhausted, it can be removed with popleft(); otherwise, it can be cycled back to the end with the rotate() method:如果该迭代器已用尽,则可以使用popleft()将其删除;否则,可以使用rotate()方法将其循环回终点:

def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
iterators = deque(map(iter, iterables))
while iterators:
try:
while True:
yield next(iterators[0])
iterators.rotate(-1)
except StopIteration:
# Remove an exhausted iterator.
iterators.popleft()

The rotate() method provides a way to implement deque slicing and deletion. rotate()方法提供了一种实现deque切片和删除的方法。For example, a pure Python implementation of del d[n] relies on the rotate() method to position elements to be popped:例如,del d[n]的纯Python实现依赖于rotate()方法来定位要弹出的元素:

def delete_nth(d, n):
d.rotate(-n)
d.popleft()
d.rotate(n)

To implement deque slicing, use a similar approach applying rotate() to bring a target element to the left side of the deque. 要实现deque切片,请使用类似的方法应用rotate()将目标元素带到deque的左侧。Remove old entries with popleft(), add new entries with extend(), and then reverse the rotation. 使用popleft()删除旧条目,使用extend()添加新条目,然后反转旋转。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.通过该方法的微小变化,很容易实现四种风格的堆栈操作,例如dupdropswapoverpickrotroll

defaultdict objects对象

classcollections.defaultdict(default_factory=None, /[, ...])

Return a new dictionary-like object. 返回一个新的类似字典的对象。defaultdict is a subclass of the built-in dict class. defaultdict是内置dict类的一个子类。It overrides one method and adds one writable instance variable. 它重写一个方法并添加一个可写实例变量。The remaining functionality is the same as for the dict class and is not documented here.其余功能与dict类相同,此处不作说明。

The first argument provides the initial value for the default_factory attribute; it defaults to None. 第一个参数为default_factory属性提供初始值;默认为NoneAll remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.所有剩余的参数被视为与传递给dict构造函数相同,包括关键字参数。

defaultdict objects support the following method in addition to the standard dict operations:除标准dict操作外,对象还支持以下方法:

__missing__(key)

If the default_factory attribute is None, this raises a KeyError exception with the key as argument.如果default_factory属性为None,则会引发以key为参数的KeyError异常。

If 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.如果default_factory不是None,则在没有参数的情况下调用它以提供给定key的默认值,该值将插入键的字典中,并返回。

If calling default_factory raises an exception this exception is propagated unchanged.如果调用default_factory引发异常,则此异常会原封不动地传播。

This method is called by the __getitem__() method of the dict class when the requested key is not found; whatever it returns or raises is then returned or raised by __getitem__().当未找到请求的键时,dict类的__getitem__()方法调用此方法;然后,它返回或引发的任何内容都由__getitem__()返回或引发。

Note that __missing__() is not called for any operations besides __getitem__(). 请注意,除了__getitem__()之外,没有为任何操作调用__missing__()This means that get() will, like normal dictionaries, return None as a default rather than using default_factory.这意味着get()将像普通字典一样,返回None作为默认值,而不是使用default_factory

defaultdict objects support the following instance variable:对象支持以下实例变量:

default_factory

This attribute is used by the __missing__() method; it is initialized from the first argument to the constructor, if present, or to None, if absent.此属性由__missing__()方法使用;它从第一个参数初始化为构造函数(如果存在),或初始化为None(如果不存在)。

Changed in version 3.9:版本3.9中更改: Added merge (|) and update (|=) operators, specified in PEP 584.添加了PEP 584中指定的合并(|)和更新(|=)运算符。

defaultdict Examples示例

Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists:使用list作为default_factory,可以很容易地将键值对序列分组到列表字典中:

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. 当第一次遇到每个键时,它不在映射中;因此,使用default_factory函数自动创建一个条目,该函数返回一个空listThe 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 list.append() operation adds another value to the list. 然后,list.append()操作将值附加到新列表。当再次遇到键时,查找会正常进行(返回该键的列表),并且list.append()操作会向列表中添加另一个值。This technique is simpler and faster than an equivalent technique using dict.setdefault():此技术比使用dict.setdefault()的等效技术更简单、更快:

>>> d = {}
>>> for k, v in s:
... d.setdefault(k, []).append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

Setting the default_factory to int makes the defaultdict useful for counting (like a bag or multiset in other languages):default_factory设置为int可以使defaultdict用于计数(如其他语言中的bag或multiset):

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> sorted(d.items())
[('i', 4), ('m', 1), ('p', 2), ('s', 4)]

When a letter is first encountered, it is missing from the mapping, so the default_factory function calls int() to supply a default count of zero. 当第一次遇到字母时,它在映射中丢失,因此default_factory函数调用int()以提供默认的零计数。The increment operation then builds up the count for each letter.然后,递增操作建立每个字母的计数。

The function int() which always returns zero is just a special case of constant functions. 始终返回零的函数int()只是常数函数的特例。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):创建常量函数的更快更灵活的方法是使用lambda函数,该函数可以提供任何常量值(不仅仅是零):

>>> def constant_factory(value):
... return lambda: value
>>> d = defaultdict(constant_factory('<missing>'))
>>> d.update(name='John', action='ran')
>>> '%(name)s %(action)s to %(object)s' % d
'John ran to <missing>'

Setting the default_factory to set makes the defaultdict useful for building a dictionary of sets:default_factory设置为set可以使defaultdict用于构建集合字典:

>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
>>> d = defaultdict(set)
>>> for k, v in s:
... d[k].add(v)
...
>>> sorted(d.items())
[('blue', {2, 4}), ('red', {1, 3})]

namedtuple() Factory Function for Tuples with Named Fields具有命名字段的元组的工厂函数

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.它们可以在任何使用正则元组的地方使用,并增加了按名称而不是按位置索引访问字段的能力。

collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

Returns a new tuple subclass named typename. 返回名为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 __repr__() method which lists the tuple contents in a name=value format.子类的实例还有一个有用的docstring(带有typenamefield_name)和一个有用的__repr__()方法,该方法以name=value的格式列出元组内容。

The field_names are a sequence of strings such as ['x', 'y']. field_names是一系列字符串,例如['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'.或者,field_names可以是单个字符串,每个字段名由空格和/或逗号分隔,例如'x y''x, y'

Any valid Python identifier may be used for a fieldname except for names starting with an underscore. 除以下划线开头的名称外,任何有效的Python标识符都可以用于字段名。Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as class, for, return, global, pass, or raise.有效标识符由字母、数字和下划线组成,但不能以数字或下划线开头,也不能是keyword,如classforreturnglobalpassraise

If rename is true, invalid fieldnames are automatically replaced with positional names. 如果renametrue,则无效的字段名将自动替换为位置名。For example, ['abc', 'def', 'ghi', 'abc'] is converted to ['abc', '_1', 'ghi', '_3'], eliminating the keyword def and the duplicate fieldname abc.例如,['abc', 'def', 'ghi', 'abc']被转换为['abc', '_1', 'ghi', '_3'],从而消除了关键字def和重复的字段名abc

defaults can be None or an iterable of default values. defaults可以是None或默认值的iterableSince fields with a default value must come after any fields without a default, the defaults are applied to the rightmost parameters. 由于具有默认值的字段必须位于任何没有默认值的字段之后,因此defaults应用于最右侧的参数。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.例如,如果字段名为['x', 'y', 'z'],默认值为(1, 2),那么x将是必需的参数,y将默认为1,z将默认为2。

If module is defined, the __module__ attribute of the named tuple is set to that value.如果定义了module,则将命名元组的__module__属性设置为该值。

Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.命名元组实例没有每个实例字典,因此它们是轻量级的,不需要比常规元组更多的内存。

To support pickling, the named tuple class should be assigned to a variable that matches typename.为了支持pickle,应将命名元组类分配给与typename匹配的变量。

Changed in version 3.1:版本3.1中更改: Added support for rename.添加了对rename的支持。

Changed in version 3.6:版本3.6中更改: The verbose and rename parameters became keyword-only arguments.verboserename参数变成了纯关键字参数。

Changed in version 3.6:版本3.6中更改: Added the module parameter.添加了module参数。

Changed in version 3.7:版本3.7中更改: Removed the verbose parameter and the _source attribute.删除了verbose参数和_source属性。

Changed in version 3.7:版本3.7中更改: Added the defaults parameter and the _field_defaults attribute.添加了defaults参数和_field_defaults属性。

>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> p # readable __repr__ with a name=value style
Point(x=11, y=22)

Named tuples are especially useful for assigning field names to result tuples returned by the csv or sqlite3 modules:命名元组对于将字段名分配给csvsqlite3模块返回的结果元组特别有用:

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
print(emp.name, emp.title)

import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
print(emp.name, emp.title)

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.为了防止与字段名冲突,方法和属性名以下划线开头。

classmethodsomenamedtuple._make(iterable)

Class method that makes a new instance from an existing sequence or iterable.从现有序列或iterable生成新实例的类方法。

>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)
somenamedtuple._asdict()

Return a new dict which maps field names to their corresponding values:返回一个新的dict,它将字段名映射到其相应的值:

>>> p = Point(x=11, y=22)
>>> p._asdict()
{'x': 11, 'y': 22}

Changed in version 3.1:版本3.1中更改: Returns an OrderedDict instead of a regular dict.返回OrderedDict而不是常规dict

Changed in version 3.8:版本3.8中更改: Returns a regular dict instead of an OrderedDict. 返回常规dict而不是OrderedDictAs of Python 3.7, regular dicts are guaranteed to be ordered. 从Python 3.7开始,保证对常规dict进行排序。If the extra features of OrderedDict are required, the suggested remediation is to cast the result to the desired type: OrderedDict(nt._asdict()).如果需要OrderedDict的额外功能,建议的补救措施是将结果转换为所需的类型:OrderedDict(nt._asdict())

somenamedtuple._replace(**kwargs)

Return a new instance of the named tuple replacing specified fields with new values:返回命名元组的新实例,用新值替换指定字段:

>>> p = Point(x=11, y=22)
>>> p._replace(x=33)
Point(x=33, y=22)
>>> for partnum, record in inventory.items():
... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
somenamedtuple._fields

Tuple of strings listing the field names. 列出字段名的字符串元组。Useful for introspection and for creating new named tuple types from existing named tuples.用于内省和从现有命名元组创建新的命名元组类型。

>>> p._fields            # view the field names
('x', 'y')
>>> Color = namedtuple('Color', 'red green blue')
>>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)
somenamedtuple._field_defaults

Dictionary mapping field names to default values.字典将字段名称映射到默认值。

>>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
>>> Account._field_defaults
{'balance': 0}
>>> Account('premium')
Account(type='premium', balance=0)

To retrieve a field whose name is stored in a string, use the getattr() function:要检索名称存储在字符串中的字段,请使用getattr()函数:

>>> getattr(p, 'x')
11

To convert a dictionary to a named tuple, use the double-star-operator (as described in Unpacking Argument Lists):要将字典转换为命名元组,请使用双星运算符(如解包参数列表中所述):

>>> d = {'x': 11, 'y': 22}
>>> Point(**d)
Point(x=11, y=22)

Since a named tuple is a regular Python class, it is easy to add or change functionality with a subclass. 由于命名元组是一个常规的Python类,因此很容易使用子类添加或更改功能。Here is how to add a calculated field and a fixed-width print format:以下是如何添加计算字段和固定宽度打印格式:

>>> class Point(namedtuple('Point', ['x', 'y'])):
... __slots__ = ()
... @property
... def hypot(self):
... return (self.x ** 2 + self.y ** 2) ** 0.5
... def __str__(self):
... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
>>> for p in Point(3, 4), Point(14, 5/7):
... print(p)
Point: x= 3.000 y= 4.000 hypot= 5.000
Point: x=14.000 y= 0.714 hypot=14.018

The subclass shown above sets __slots__ to an empty tuple. 上面显示的子类将__slots__设置为空元组。This helps keep memory requirements low by preventing the creation of instance dictionaries.这有助于通过防止创建实例字典来保持较低的内存需求。

Subclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the _fields attribute:子类化对于添加新的存储字段无效。相反,只需从_fields属性创建一个新的命名元组类型:

>>> Point3D = namedtuple('Point3D', Point._fields + ('z',))

Docstrings can be customized by making direct assignments to the __doc__ fields:可以通过直接分配到__doc__字段来自定义docstring:

>>> Book = namedtuple('Book', ['id', 'title', 'authors'])
>>> Book.__doc__ += ': Hardcover book in active collection'
>>> Book.id.__doc__ = '13-digit ISBN'
>>> Book.title.__doc__ = 'Title of first printing'
>>> Book.authors.__doc__ = 'List of authors sorted by last name'

Changed in version 3.5:版本3.5中更改: Property docstrings became writeable.属性docstring变为可写。

See also另请参见

  • See typing.NamedTuple for a way to add type hints for named tuples. 有关为命名元组添加类型提示的方法,请参阅typing.NamedTupleIt also provides an elegant notation using the class keyword:它还使用class关键字提供了一种优雅的表示法:

    class Component(NamedTuple):
    part_number: int
    weight: float
    description: Optional[str] = None
  • See types.SimpleNamespace() for a mutable namespace based on an underlying dictionary instead of a tuple.请参阅types.SimpleNamespace(),了解基于底层字典而不是元组的可变命名空间。

  • The dataclasses module provides a decorator and functions for automatically adding generated special methods to user-defined classes.dataclasses模块提供了一个装饰器和函数,用于自动将生成的特殊方法添加到用户定义的类中。

OrderedDict objects对象

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 dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).由于内置的dict类获得了记住插入顺序的能力(这一新行为在Python 3.7中得到了保证),它们变得不那么重要了。

Some differences from dict still remain:dict的一些差异仍然存在:

  • The regular dict was designed to be very good at mapping operations. 常规dict被设计为非常擅长映射操作。Tracking insertion order was secondary.跟踪插入顺序是次要的。

  • The OrderedDict was designed to be good at reordering operations. OrderedDict旨在擅长重新排序操作。Space efficiency, iteration speed, and the performance of update operations were secondary.空间效率、迭代速度和更新操作的性能是次要的。

  • The OrderedDict algorithm can handle frequent reordering operations better than dict. OrderedDict算法比dict更好地处理频繁的重新排序操作。As shown in the recipes below, this makes it suitable for implementing various kinds of LRU caches.如下面的配方所示,这使得它适合实现各种LRU缓存。

  • The equality operation for OrderedDict checks for matching order.OrderedDict的相等操作检查匹配顺序。

    A regular dict can emulate the order sensitive equality test with p == q and all(k1 == k2 for k1, k2 in zip(p, q)).常规dict可以模拟顺序敏感的等式测试,其中p == q and all(k1 == k2 for k1, k2 in zip(p, q))

  • The popitem() method of OrderedDict has a different signature. It accepts an optional argument to specify which item is popped.OrderedDictpopitem()方法具有不同的签名。它接受一个可选参数来指定弹出哪个项。

    A regular dict can emulate OrderedDict’s od.popitem(last=True) with d.popitem() which is guaranteed to pop the rightmost (last) item.常规dict可以使用dpopitem()模拟OrderedDict的od.popitem(last=True)d.popitem()保证弹出最右边(最后面)的项。

    A regular 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.常规dict可以用(k := next(iter(d)), d.pop(k))模拟orderedict的od.popitem(last=False),如果最左边的(第一个)项存在,它将返回并删除它。

  • OrderedDict has a move_to_end() method to efficiently reposition an element to an endpoint.OrderedDict有一个move_to_end()方法,可以有效地将元素重新定位到端点。

    A regular 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.常规dict可以模拟OrderedDict的od.move_to_end(k, last=True),其中d[k] = d.pop(k),这将把键及其相关值移动到最右边(最后面)的位置。

    A regular 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.对于OrderedDict的od.move_to_end(k, last=False),常规dict没有有效的等价物,它将键及其相关值移动到最左侧(第一个)位置。

  • Until Python 3.8, dict lacked a __reversed__() method.在Python 3.8之前,dict缺少一个__reversed__()方法。

classcollections.OrderedDict([items])

Return an instance of a dict subclass that has methods specialized for rearranging dictionary order.返回dict子类的实例,该子类具有专门用于重新排列字典顺序的方法。

New in version 3.1.版本3.1中新增。

popitem(last=True)

The popitem() method for ordered dictionaries returns and removes a (key, value) pair. 用于有序字典的popitem()方法返回并删除(键,值)对。The pairs are returned in LIFO order if last is true or FIFO order if false.如果lasttrue,则按后进先出顺序返回配对;如果为false,则先进先出顺序返回配对。

move_to_end(key, last=True)

Move an existing key to either end of an ordered dictionary. 将现有key移动到有序字典的任一端。The item is moved to the right end if last is true (the default) or to the beginning if last is false. 如果lasttrue(默认值),则项目移动到右端;如果lastfalse,则项目移动到开头。Raises KeyError if the key does not exist:如果key不存在,则引发KeyError

>>> d = OrderedDict.fromkeys('abcde')
>>> d.move_to_end('b')
>>> ''.join(d)
'acdeb'
>>> d.move_to_end('b', last=False)
>>> ''.join(d)
'bacde'

New in version 3.2.版本3.2中新增。

In addition to the usual mapping methods, ordered dictionaries also support reverse iteration using reversed().除了常用的映射方法外,有序字典还支持使用reversed()进行反向迭代。

Equality tests between OrderedDict objects are order-sensitive and are implemented as list(od1.items())==list(od2.items()). OrderedDict对象之间的相等性测试是顺序敏感的,并作为list(od1.items())==list(od2.items())实现。Equality tests between OrderedDict objects and other Mapping objects are order-insensitive like regular dictionaries. OrderedDict对象和其他Mapping对象之间的相等性测试与常规字典一样不区分顺序。This allows OrderedDict objects to be substituted anywhere a regular dictionary is used.这允许在使用常规字典的任何地方替换OrderedDict对象。

Changed in version 3.5:版本3.5中更改: The items, keys, and values views of OrderedDict now support reverse iteration using reversed().OrderedDict的项、键和值视图现在支持使用reversed()进行反向迭代。

Changed in version 3.6:版本3.6中更改: With the acceptance of PEP 468, order is retained for keyword arguments passed to the OrderedDict constructor and its update() method.随着PEP 468的接受,传递给OrderedDict构造函数及其update()方法的关键字参数的顺序保持不变。

Changed in version 3.9:版本3.9中更改: Added merge (|) and update (|=) operators, specified in PEP 584.添加了PEP 584中指定的合并(|)和更新(|=)运算符。

OrderedDict Examples and Recipes示例和配方

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:如果新条目覆盖现有条目,则会更改原始插入位置并将其移动到末尾:

class LastUpdatedOrderedDict(OrderedDict):
'Store items in the order the keys were last added'
def __setitem__(self, key, value):
super().__setitem__(key, value)
self.move_to_end(key)

An OrderedDict would also be useful for implementing variants of functools.lru_cache():OrderedDict对于实现functools.lru_cache()的变体也很有用:

from time import time
class TimeBoundedLRU:
"LRU Cache that invalidates and refreshes old entries."

def __init__(self, func, maxsize=128, maxage=30):
self.cache = OrderedDict() # { args : (timestamp, result)}
self.func = func
self.maxsize = maxsize
self.maxage = maxage

def __call__(self, *args):
if args in self.cache:
self.cache.move_to_end(args)
timestamp, result = self.cache[args]
if time() - timestamp <= self.maxage:
return result
result = self.func(*args)
self.cache[args] = time(), result
if len(self.cache) > self.maxsize:
self.cache.popitem(0)
return result
class MultiHitLRUCache:
""" LRU cache that defers caching a result until
it has been requested multiple times.
To avoid flushing the LRU cache with one-time requests,
we don't cache until a request has been made more than once.

"""

def __init__(self, func, maxsize=128, maxrequests=4096, cache_after=1):
self.requests = OrderedDict() # { uncached_key : request_count }
self.cache = OrderedDict() # { cached_key : function_result }
self.func = func
self.maxrequests = maxrequests # max number of uncached requests
self.maxsize = maxsize # max number of stored return values
self.cache_after = cache_after

def __call__(self, *args):
if args in self.cache:
self.cache.move_to_end(args)
return self.cache[args]
result = self.func(*args)
self.requests[args] = self.requests.get(args, 0) + 1
if self.requests[args] <= self.cache_after:
self.requests.move_to_end(args)
if len(self.requests) > self.maxrequests:
self.requests.popitem(0)
else:
self.requests.pop(args, None)
self.cache[args] = result
if len(self.cache) > self.maxsize:
self.cache.popitem(0)
return result

UserDict objects对象

The class, UserDict acts as a wrapper around dictionary objects. UserDict充当字典对象的包装器。The need for this class has been partially supplanted by the ability to subclass directly from dict; however, this class can be easier to work with because the underlying dictionary is accessible as an attribute.直接从dict生成子类的能力部分取代了对此类的需求;然而,这个类更容易使用,因为底层字典可以作为属性访问。

classcollections.UserDict([initialdata])

Class that simulates a dictionary. 类,该类模拟字典。The instance’s contents are kept in a regular dictionary, which is accessible via the data attribute of UserDict instances. 实例的内容保存在一个常规字典中,可以通过UserDict实例的data属性访问该字典。If initialdata is provided, data is initialized with its contents; note that a reference to initialdata will not be kept, allowing it to be used for other purposes.如果提供initialdata,则使用其内容初始化data;请注意,不会保留对initialdata的引用,从而允许将其用于其他目的。

In addition to supporting the methods and operations of mappings, UserDict instances provide the following attribute:除了支持映射的方法和操作外,UserDict实例还提供以下属性:

data

A real dictionary used to store the contents of the UserDict class.用于存储UserDict类内容的真实字典。

UserList objects对象

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.通过这种方式,可以向列表中添加新行为。

The need for this class has been partially supplanted by the ability to subclass directly from list; however, this class can be easier to work with because the underlying list is accessible as an attribute.直接从list中生成子类的能力部分取代了对此类的需求;然而,这个类更容易使用,因为底层列表可以作为属性访问。

classcollections.UserList([list])

Class that simulates a list. 模拟列表的类。The instance’s contents are kept in a regular list, which is accessible via the data attribute of UserList instances. 实例的内容保存在一个常规列表中,可以通过UserList实例的data属性访问该列表。The instance’s contents are initially set to a copy of list, defaulting to the empty list []. 实例的内容最初设置为list的副本,默认为空列表[]list can be any iterable, for example a real Python list or a UserList object.list可以是任何可迭代对象,例如真实的Python列表或UserList对象。

In addition to supporting the methods and operations of mutable sequences, UserList instances provide the following attribute:除了支持可变序列的方法和操作外,UserList实例还提供以下属性:

data

A real list object used to store the contents of the UserList class.用于存储UserList类内容的实list对象。

Subclassing requirements:子分类要求: Subclasses of UserList are expected to offer a constructor which can be called with either no arguments or one argument. UserList的子类应该提供一个构造函数,该构造函数可以用无参数或一个参数调用。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.为此,它假设可以使用单个参数调用构造函数,该参数是用作数据源的序列对象。

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.如果派生类不希望符合此要求,则需要重写该类支持的所有特殊方法;关于这种情况下需要提供的方法,请咨询来源。

UserString objects对象

The class, UserString acts as a wrapper around string objects. UserString类充当字符串对象的包装器。The need for this class has been partially supplanted by the ability to subclass directly from str; however, this class can be easier to work with because the underlying string is accessible as an attribute.直接从str中生成子类的能力部分取代了对此类的需求;然而,这个类更容易使用,因为底层字符串可以作为属性访问。

classcollections.UserString(seq)

Class that simulates a string object. 类,该类模拟字符串对象。The instance’s content is kept in a regular string object, which is accessible via the data attribute of UserString instances. 实例的内容保存在常规字符串对象中,可以通过UserString实例的data属性访问该对象。The instance’s contents are initially set to a copy of seq. 实例的内容最初设置为seq的副本。The seq argument can be any object which can be converted into a string using the built-in str() function.seq参数可以是任何可以使用内置str()函数转换为字符串的对象。

In addition to supporting the methods and operations of strings, UserString instances provide the following attribute:除了支持字符串的方法和操作外,UserString实例还提供以下属性:

data

A real str object used to store the contents of the UserString class.用于存储UserString类内容的真实str对象。

Changed in version 3.5:版本3.5中更改: New methods __getnewargs__, __rmod__, casefold, format_map, isprintable, and maketrans.新方法__getnewargs____rmod__casefoldformat_mapisprintablemaketrans