使用dicts代码和变量

时间:2014-03-23 20:40:49

标签: python dictionary scope switch-statement

我有以下代码终于可以了!但作为一个Python新手,我想看看是否有更好的方法来做到这一点。特别是,作为蒙特卡罗化学动力学项目的一部分,底部的环路必须非常快。这应该快吗?有没有更好(更pythonic)的方式来做这个比捆绑词典中的所有东西?这些词典可能有多达数百个条目。谢谢!

def split(pops,src, dst): pops[src] -= 1; pops[dst] += 2
def join(pops,src, dst) : pops[src] -= 1; pops[dst] += 2
def jump(pops,src, dst) : pops[src] -= 1; pops[dst] += 2

j1, j2, s1, s2, m1, m2, d1, d2 = .1, .1, .1, .1, .1, .1, .1, .1

pops = {'mon1':1000,    # initial population of monomers in regime 1
        'dim1':1000,    #        "              dimers   "
        'mon2':1000,    # etc.
        'dim2':1000}

trns = {'j1':(j1, join, 'mon1', 'dim1'),  # j1=prob of 2 monomers joining to form a dimer
        'j2':(j2, join, 'mon2', 'dim2'),  
        's1':(s1, split,'dim1', 'mon1'),
        's2':(s2, split,'dim2', 'mon2'),
        'm1':(m1, jump ,'mon1', 'mon2'),
        'm2':(m2, jump ,'mon2', 'mon1'),
        'd1':(d1, jump ,'dim1', 'dim2'),
        'd2':(d2, jump ,'dim2', 'dim1')}    

while True: 
    event = 's1' # this would be derived from rand(), called many times

    action  = trns[event][1]   # either join, split or jump
    source  = trns[event][2]   # source species
    dest    = trns[event][3]   # destination species

    action(pops, source, dest) # make the function call to update populations
    break

print pops

1 个答案:

答案 0 :(得分:0)

您可能会发现使用已经过优化的库来进行蒙特卡罗模拟更容易,这样可以让您在问题域中更直接地工作,而不是在python代码编写域中。例如,参见python库scipy中的Monte Carlo。 http://www.scipy.org/topical-software.html