如何在python字典中使用lambda函数

时间:2014-03-24 13:49:42

标签: python dictionary lambda

我正在尝试在python词典中使用lambda函数来创建一个简单的化学属性数据库。这段代码

Psat = dict()
Psat['acetone'] = lambda T: 10**(7.02447 - 1161.0/(224 + T))
Psat['benzene'] = lambda T: 10**(6.89272 - 1203.531/(219.888 + T))
Psat['ethanol'] = lambda T: 10**(8.04494 - 1554.3/(222.65 + T))
Psat['toluene'] = lambda T: 10**(6.95805 - 1346.773/(219.693 + T))

K = dict()
for n in Psat.keys():
    K[n] = lambda P,T: Psat[n](T)/P

P = 760
T = 65

print "Pressure     {:6.2f} [mmHg]".format(P)
print "Temperature  {:6.2f} [deg C]".format(T)
print "K-factors:"
for n in K.keys():
    print "   {:s}  {:7.3f}".format(n,K[n](P,T))

按预期工作,返回

Pressure     760.00 [mmHg]
Temperature   65.00 [deg C]
K-factors:
   benzene    0.613
   acetone    1.338
   ethanol    0.576
   toluene    0.222

但是,此代码没有。

for n,k in K.iteritems():
    print k(P,T),K[n]

def test():
    for (n,k) in K.iteritems():
        print k(P,T),k

test()

事实上,这些会带来不同的结果。

0.612816477285 <function <lambda> at 0x1072de500>
1.33768965865 <function <lambda> at 0x1072de5f0>
0.57634791331 <function <lambda> at 0x1072de578>
0.222137215724 <function <lambda> at 0x1072de668>
0.222137215724 <function <lambda> at 0x1072de500>
0.222137215724 <function <lambda> at 0x1072de5f0>
0.222137215724 <function <lambda> at 0x1072de578>
0.222137215724 <function <lambda> at 0x1072de668>

我正在使用Anaconda发行版在IPython笔记本中使用Python 2.7开发它。有什么建议吗?

0 个答案:

没有答案