为蟒蛇的字典中保证在迭代?
-
20-09-2019 - |
题
我目前正在执行一个复杂微生物食物网的使用Python 这.整合。歌颂.我需要的能力,容易添加物种和反应系统,因此我要代码了一些很一般。我的计划看起来像这样的东西:
class Reaction(object):
def __init__(self):
#stuff common to all reactions
def __getReactionRate(self, **kwargs):
raise NotImplementedError
... Reaction subclasses that
... implement specific types of reactions
class Species(object):
def __init__(self, reactionsDict):
self.reactionsDict = reactionsDict
#reactionsDict looks like {'ReactionName':reactionObject, ...}
#stuff common to all species
def sumOverAllReactionsForThisSpecies(self, **kwargs):
#loop over all the reactions and return the
#cumulative change in the concentrations of all solutes
...Species subclasses where for each species
... are defined and passed to the superclass constructor
class FermentationChamber(object):
def __init__(self, speciesList, timeToSolve, *args):
#do initialization
def step(self):
#loop over each species, which in turn loops
#over each reaction inside it and return a
#cumulative dictionary of total change for each
#solute in the whole system
if __name__==__main__:
f = FermentationChamber(...)
o = ode(...) #initialize ode solver
while o.successful() and o.t<timeToSolve:
o.integrate()
#process o.t and o.y (o.t contains the time points
#and o.y contains the solution matrix)
因此,问题是,当我迭代的字典中 Species.sumOverAllReactionsForThisSpecies()
和 FermentationChamber.step()
, 是的迭代了字典的保证是相同的,如果没有元素添加或删除的字典之间第一个和最后一个迭代的?是的,我可以假设为的顽固阵创建在每次迭代,从字典不会改变?例如,如果一词典有的格式{'糖':10,'果糖':12}如果一系列创造了这个词典将 总是 具有相同的顺序(不论是什么,以,只要它确定性).
对不起大型的员额,我只是想让你知道我从哪里来的.
解决方案
蟒蛇3.1有一个 集合。OrderedDict 类,可用于这一目的。这是非常有效的:"大-O运行时间为所有的方法都是一样对常规的词典。"
的 代码OrderedDict 本身是兼容蟒蛇2.x,虽然某些继承的方法(从 _abcoll 模块)使用Python3-只有功能。然而,他们可以修改到2。x代码用最少的努力。
其他提示
是,如果它没有被修改的相同的顺序保证。
请参阅该文档此处。
修改强>
如果关于变更的值(但不是添加/删除的键)会影响顺序,这是在C-源的注释这样说:
/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
* dictionary if it's merely replacing the value for an existing key.
* This means that it's safe to loop over a dictionary with PyDict_Next()
* and occasionally replace a value -- but you can't insert new keys or
* remove them.
*/
似乎它的未实现的细节,但语言的要求。
本发明提供的没有修改到字典制成,答案是肯定的。 查看的文档这里。
然而,词典由性质在Python无序的。在一般情况下,它不依赖字典对于敏感排序的数据的最佳实践。
一个更可靠的解决方案的一个例子是 Django的SortedDict数据结构。
如果您想要的顺序是一致的,我会做一些强制特定的顺序。虽然你也许能说服自己,顺序是有保证的,你可能是正确的,它似乎脆弱对我来说,这将是神秘的给其他开发者。
例如,您强调的总是在你的问题的。它是重要的,它是在Python 2.5和2.6相同的顺序? 2.6和3.1? CPython的和Jython?我不会指望那些。
此外,建议不依赖于这样的事实的字典顺序是非随机的。
如果你想有一个内置的解决方案来分拣你的字典阅读 HTTP:// WWW .python.org的/ dev / PEPS / PEP-0265 /
下面是最相关的材料:
此PEP被拒绝,因为需要它也基本 通过Py2.4的排序()内置函数满足:
>>> sorted(d.iteritems(), key=itemgetter(1), reverse=True)
[('b', 23), ('d', 17), ('c', 5), ('a', 2), ('e', 1)]
or for just the keys:
>>> sorted(d, key=d.__getitem__, reverse=True)
['b', 'd', 'c', 'a', 'e']
Also, Python 2.5's heapq.nlargest() function addresses the common use
case of finding only a few of the highest valued items:
>>> nlargest(2, d.iteritems(), itemgetter(1))
[('b', 23), ('d', 17)]