문제

나는 현재 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} 형식이있는 경우,이 사전에서 생성 된 배열이 언제나 순서가 동일합니다 (순서가 결정적이라면 그 순서가 무엇인지는 중요하지 않음).

메가 포스트에 대해 죄송합니다. 내가 어디에서 왔는지 알려 드리고 싶었습니다.

도움이 되었습니까?

해결책

파이썬 3.1은 a Collections.OrderEddict 이 목적으로 사용할 수있는 수업. "모든 방법에 대한 Big-O Running Time은 일반 사전과 동일합니다."

그만큼 OrderedDict에 대한 코드 자체는 Python 2.x와 호환되지만 일부 상속 된 방법 ( _abcoll 모듈)은 Python 3 전용 기능을 사용합니다. 그러나 최소한의 노력으로 2.x 코드로 수정할 수 있습니다.

다른 팁

예, 수정되지 않은 경우 동일한 주문이 보장됩니다.

문서를 참조하십시오 여기.

편집하다:

값을 변경하지만 (키를 추가/키를 추가하지 않음) 순서에 영향을 미치는 경우 C-Source의 의견이 다음과 같습니다.

/* 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.
 */

구현 세부 사항이 아니라 언어의 요구 사항 인 것 같습니다.

제공 아니요 사전에 수정이 이루어지며 대답은 예입니다. 여기서 문서를 참조하십시오.

그러나 사전은 파이썬에서 본질적으로 변하지 않습니다. 일반적으로 민감한 정렬 데이터에 대한 사전에 의존하는 것이 가장 좋은 관행이 아닙니다.

보다 강력한 솔루션의 예는 Django의 SortedDict 데이터 구조.

순서가 일관되기를 원한다면 특정 주문을 강요하기 위해 무언가를 할 것입니다. 당신은 질서가 보장되고 당신이 옳을 수도 있다고 스스로에게 확신 할 수 있지만, 그것은 나에게 깨지기 쉬운 것처럼 보이며 다른 개발자들에게 신비 할 것입니다.

예를 들어, 당신은 강조합니다 언제나 당신의 질문에. Python 2.5 및 2.6에서 동일한 순서가 중요합니까? 2.6 및 3.1? Cpython과 Jython? 나는 그것에 의지하지 않을 것입니다.

또한 사전 주문이 비 랜덤이라는 사실에 의존하지 않는 것이 좋습니다.

내장 된 솔루션을 정렬하여 사전 읽기를 정렬하려면 http://www.python.org/dev/peps/pep-0265/

가장 관련성이 높은 자료는 다음과 같습니다.

이 PEP는 PY2.4의 SINTED () 내장 기능에 의해 크게 충족 되었기 때문에 거부됩니다.

    >>> 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