gpt4 book ai didi

python - Python 字典的顺序是否在迭代中得到保证?

转载 作者:IT老高 更新时间:2023-10-28 21:56:14 25 4
gpt4 key购买 nike

我目前正在使用 SciPy.integrate.ode 在 Python 中实现一个复杂的微生物食物网。 .我需要能够轻松地将物种和 react 添加到系统中,所以我必须编写一些非常通用的代码。我的方案如下所示:

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() 中的字典时,字典的迭代顺序是否得到保证如果在第一次和最后一次迭代之间没有从字典中添加或删除任何元素,是否相同?也就是说,我可以假设字典中每次迭代创建的 numpy 数组的顺序不会改变吗?例如,如果字典的格式为 {'Glucose':10, 'Fructose':12},如果从该字典创建的数组将总是具有相同的顺序(不管是什么该顺序是确定性的)。

对不起,我只是想让你知道我来自哪里。

最佳答案

是的,如果不修改,保证相同的顺序。

查看文档 here .

编辑:

关于更改值(但不添加/删除键)是否会影响顺序,这是 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 - Python 字典的顺序是否在迭代中得到保证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2053021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com