質問

私は現在、Python で複雑な微生物の食物網を実装しています。 SciPy.integrate.ode. 。システムに種や反応を簡単に追加できる機能が必要なので、非常に一般的なものをコード化する必要があります。私のスキームは次のようになります。

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} である場合、この辞書から作成された配列は次のようになります。 いつも 同じ順序を持ちます (順序が決定的である限り、その順序は問題ではありません)。

大量の投稿で申し訳ありませんが、私がどこから来たのかをお知らせしたかっただけです。

役に立ちましたか?

解決

Python 3.1 には、 コレクション.OrderedDict この目的に使用できるクラス。これも非常に効率的です。「すべてのメソッドの Big-O の実行時間は、通常の辞書の場合と同じです。」

OrderedDictのコード それ自体は Python 2.x と互換性がありますが、一部のメソッドは ( _abcoll module) は Python 3 のみの機能を使用します。ただし、最小限の労力で 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の?私はそれらを当てにしません。

私も、辞書順が非ランダムである事実に依存しないことをお勧めします。

// WWW:あなたはあなたを仕分けするソリューションで構築したい場合は、

HTTPを読んディクショナリ.python.orgは/ dev /のPEP / 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)]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top