Adding that [0] in there really jacks things up so to say. Or even having to specify ['STATION'] every time is a bit of a nuisance.
所以只需将precip['STATION'][0]存储在一个变量中:>>> precip0 = precip['STATION'][0]
现在,您可以重复使用它:
^{pr2}$
如果您知道API总是只返回一个站点,并且您永远不需要该站点的数据以外的任何内容,那么可以将其放入包装器函数中:def precipitation_obs(stid, start, end, units):
# your existing code, which assigns something to result
return result['STATION'][0]
如果你担心这里的“效率”,别担心。首先,这不是复制任何东西,它只是对已经存在的同一个对象进行另一个引用它需要不到一微秒的时间,浪费大约8个字节。实际上,它可以节省内存,因为如果不存储整个dict,只存储子dict,Python可以对结构的其余部分进行垃圾收集。而且,更重要的是,在(1)您的代码正常工作并且(2)您知道这是一个瓶颈之前,这种微优化首先是不值得担心的。在Should I use the simpleJSON module to help here?
为什么你认为这会有帮助?作为its readme says:simplejson is the externally maintained development version of the json library included with Python 2.6 and Python 3.0, but maintains backwards compatibility with Python 2.5.
换句话说,它要么是stdlib中已有的代码,要么是该代码的旧版本。在
有时,不同的库,如^{},可以帮助您——例如,如果JSON结构太大,以至于您无法将整个内容解析到内存中,或者非常复杂,以至于可以更容易地用SAX风格来描述您想要的东西。但这与这里无关。在