collections
— Container datatypes容器数据类型¶
Source code: Lib/collections/__init__.py
This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, 该模块实现专门的容器数据类型,提供Python通用内置容器,dict
, list
, set
, and tuple
.dict
、list
、set
和tuple
的替代品。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.该类可用于模拟嵌套作用域,并在模板制作中很有用。
-
class
collections.
ChainMap
(*maps)¶ AChainMap
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.相反,写入、更新和删除仅在第一个映射上操作。AChainMap
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 tod.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']-
See also
The MultiContext class in the Enthought CodeTools package has options to support writing to any mapping in the chain.Enthught CodeTools包中的MultiContext
类具有支持写入链中任何映射的选项。Django’s Context class for templating is a read-only chain of mappings.Django用于模板化的上下文类是一个只读映射链。It also features pushing and popping of contexts similar to the它还具有推送和弹出上下文的功能,类似于new_child()
method and theparents
property.new_child()
方法和parents
属性。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.嵌套上下文配方具有控制写入和其他突变是否仅适用于第一个映射或链中的任何映射的选项。A greatly simplified read-only version of Chainmap.链图的一个大大简化的只读版本。
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)]
-
class
collections.
Counter
([iterable-or-mapping])¶ ACounter
is adict
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.计数可以是任何整数值,包括零或负计数。TheCounter
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 argsCounter 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
0Setting 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 entryNew 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,如果元素的计数小于1,elements()
will ignore it.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如果省略n或为None
,most_common()
returns all elements in the counter.None
,most_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()
15New in version 3.10.版本3.10中新增。
The usual dictionary methods are available for通常的字典方法可用于Counter
objects except for two which work differently for counters.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此外,iterable应该是元素序列,而不是(key, value)
pairs.(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.为了帮助处理这些用例,本节记录了最小范围和类型限制。
TheCounter
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.这些值是表示计数的数字,但您可以在值字段中存储任何内容。Themost_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 forupdate()
andsubtract()
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.没有类型限制,但值类型需要支持加法、减法和比较。Theelements()
method requires integer counts.elements()
方法需要整数计数。It ignores zero and negative counts.它忽略零计数和负计数。
See also另请参见
Bag class in Smalltalk.
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对象¶
-
class
collections.
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 forpop(0)
andinsert(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如果未指定maxlen或指定为None
, deques may grow to an arbitrary length.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有界长度队列提供了类似于Unix中tail
filter in 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.计算等于x的deque
元素数。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).返回x在deque
中的位置(索引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.删除第一个出现的value。If 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 tod.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 orNone
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 从3.5版开始,__add__()
, __mul__()
, and __imul__()
.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
.dup
、drop
、swap
、over
、pick
、rot
和roll
。
defaultdict
objects对象¶
-
class
collections.
defaultdict
(default_factory=None, /[, ...])¶ Return a new dictionary-like object.返回一个新的类似字典的对象。defaultdict
is a subclass of the built-indict
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 toNone
.default_factory
属性提供初始值;默认为None
。All 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 isNone
, this raises aKeyError
exception with the key as argument.default_factory
属性为None
,则会引发以key为参数的KeyError
异常。If如果default_factory
is notNone
, 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 thedict
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, returnNone
as a default rather than usingdefault_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 toNone
, if absent.__missing__()
方法使用;它从第一个参数初始化为构造函数(如果存在),或初始化为None
(如果不存在)。
-
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
函数自动创建一个条目,该函数返回一个空list
。The 然后,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子类的实例还有一个有用的docstring(带有__repr__()
method which lists the tuple contents in aname=value
format.typename
和field_name
)和一个有用的__repr__()
方法,该方法以name=value
的格式列出元组内容。The field_names are a sequence of strings such asfield_names是一系列字符串,例如['x', 'y']
.['x', 'y']
。Alternatively, field_names can be a single string with each fieldname separated by whitespace and/or commas, for example或者,field_names可以是单个字符串,每个字段名由空格和/或逗号分隔,例如'x y'
or'x, y'
.'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
,如class、for、return、global、pass或raise。If rename is true, invalid fieldnames are automatically replaced with positional names.如果rename为true
,则无效的字段名将自动替换为位置名。For example,例如,['abc', 'def', 'ghi', 'abc']
is converted to['abc', '_1', 'ghi', '_3']
, eliminating the keyworddef
and the duplicate fieldnameabc
.['abc', 'def', 'ghi', 'abc']
被转换为['abc', '_1', 'ghi', '_3']
,从而消除了关键字def和重复的字段名abc
。defaults can bedefaults可以是None
or an iterable of default values.None
或默认值的iterable。Since 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)
, thenx
will be a required argument,y
will default to1
, andz
will default to2
.['x', 'y', 'z']
,默认值为(1, 2)
,那么x
将是必需的参数,y
将默认为1,z
将默认为2。If module is defined, the如果定义了module,则将命名元组的__module__
attribute of the named tuple is set to that value.__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.verbose和rename参数变成了纯关键字参数。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删除了verbose参数和_source
attribute._source
属性。Changed in version 3.7:版本3.7中更改:Added the defaults parameter and the添加了defaults参数和_field_defaults
attribute._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:csv
或sqlite3
模块返回的结果元组特别有用:
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.为了防止与字段名冲突,方法和属性名以下划线开头。
-
classmethod
somenamedtuple.
_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 regulardict
.OrderedDict
而不是常规dict
。Changed in version 3.8:版本3.8中更改:Returns a regular返回常规dict
instead of anOrderedDict
.dict
而不是OrderedDict
。As 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.NamedTuple
。It also provides an elegant notation using the它还使用class
keyword:class
关键字提供了一种优雅的表示法:class Component(NamedTuple):
part_number: int
weight: float
description: Optional[str] = NoneSee请参阅types.SimpleNamespace()
for a mutable namespace based on an underlying dictionary instead of a tuple.types.SimpleNamespace()
,了解基于底层字典而不是元组的可变命名空间。Thedataclasses
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.跟踪插入顺序是次要的。TheOrderedDict
was designed to be good at reordering operations.OrderedDict
旨在擅长重新排序操作。Space efficiency, iteration speed, and the performance of update operations were secondary.空间效率、迭代速度和更新操作的性能是次要的。TheOrderedDict
algorithm can handle frequent reordering operations better thandict
.OrderedDict
算法比dict
更好地处理频繁的重新排序操作。As shown in the recipes below, this makes it suitable for implementing various kinds of LRU caches.如下面的配方所示,这使得它适合实现各种LRU缓存。The equality operation forOrderedDict
checks for matching order.OrderedDict
的相等操作检查匹配顺序。A regular常规dict
can emulate the order sensitive equality test withp == 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))
。Thepopitem()
method ofOrderedDict
has a different signature. It accepts an optional argument to specify which item is popped.OrderedDict
的popitem()
方法具有不同的签名。它接受一个可选参数来指定弹出哪个项。A regular常规dict
can emulate OrderedDict’sod.popitem(last=True)
withd.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’sod.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 amove_to_end()
method to efficiently reposition an element to an endpoint.OrderedDict
有一个move_to_end()
方法,可以有效地将元素重新定位到端点。A regular常规dict
can emulate OrderedDict’sod.move_to_end(k, last=True)
withd[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对于OrderedDict的dict
does not have an efficient equivalent for OrderedDict’sod.move_to_end(k, last=False)
which moves the key and its associated value to the leftmost (first) position.od.move_to_end(k, last=False)
,常规dict
没有有效的等价物,它将键及其相关值移动到最左侧(第一个)位置。Until Python 3.8,在Python 3.8之前,dict
lacked a__reversed__()
method.dict
缺少一个__reversed__()
方法。
-
class
collections.
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.如果last为true
,则按后进先出顺序返回配对;如果为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.如果last为true
(默认值),则项目移动到右端;如果last为false
,则项目移动到开头。Raises如果key不存在,则引发KeyError
if the key does not exist: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 随着PEP 468的接受,传递给OrderedDict
constructor and its update()
method.OrderedDict
构造函数及其update()
方法的关键字参数的顺序保持不变。
Changed in version 3.9:版本3.9中更改: Added merge (添加了PEP 584中指定的合并(|
) and update (|=
) operators, specified in 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
生成子类的能力部分取代了对此类的需求;然而,这个类更容易使用,因为底层字典可以作为属性访问。
-
class
collections.
UserDict
([initialdata])¶ Class that simulates a dictionary.类,该类模拟字典。The instance’s contents are kept in a regular dictionary, which is accessible via the实例的内容保存在一个常规字典中,可以通过data
attribute ofUserDict
instances.UserDict
实例的data
属性访问该字典。If initialdata is provided,如果提供initialdata,则使用其内容初始化data
is initialized with its contents; note that a reference to initialdata will not be kept, allowing it to be used for other purposes.data
;请注意,不会保留对initialdata的引用,从而允许将其用于其他目的。In addition to supporting the methods and operations of mappings,除了支持映射的方法和操作外,UserDict
instances provide the following attribute: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
中生成子类的能力部分取代了对此类的需求;然而,这个类更容易使用,因为底层列表可以作为属性访问。
-
class
collections.
UserList
([list])¶ Class that simulates a list.模拟列表的类。The instance’s contents are kept in a regular list, which is accessible via the实例的内容保存在一个常规列表中,可以通过data
attribute ofUserList
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 alist可以是任何可迭代对象,例如真实的Python列表或UserList
object.UserList
对象。In addition to supporting the methods and operations of mutable sequences,除了支持可变序列的方法和操作外,UserList
instances provide the following attribute:UserList
实例还提供以下属性:
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
中生成子类的能力部分取代了对此类的需求;然而,这个类更容易使用,因为底层字符串可以作为属性访问。
-
class
collections.
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 ofUserString
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-inseq参数可以是任何可以使用内置str()
function.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 theUserString
class.UserString
类内容的真实str
对象。
Changed in version 3.5:版本3.5中更改:New methods新方法__getnewargs__
,__rmod__
,casefold
,format_map
,isprintable
, andmaketrans
.__getnewargs__
、__rmod__
、casefold
、format_map
、isprintable
和maketrans
。-