为了更详细的了解,我附上了一个文件的链接:Actual file
我在列表中有数据,其语法类似于:
i = [a.b>c.d , e.f.g>h.i.j ]
例如,列表中的每个元素都有多个子元素,以".“分隔。和">“。
for i in range(0, len(l)):
reac={}
reag={}
t = l[i].split(">")
REAC = t[0]
Reac = REAC.split(".")
for o in range(len(Reac)):
reaco = "https://ai.chemistryinthecloud.com/smilies/" + Reac[o]
respo = requests.get(reaco)
reac[o] ={"Smile":Reac[o],"Details" :respo.json()}
if (len(t) != 1):
REAG = t[1]
Reag = REAG.split(".")
for k in range(len(Reag)):
reagk = "https://ai.chemistryinthecloud.com/smilies/" + Reag[k]
repo = requests.get(reagk)
reag[k] = {"Smile": Reag[k], "Details" :repo.json()}
res = {"Reactants": list(reac.values()), "Reagents": list(reag.values())}
boo.append(res)
else:
res = {"Reactants": list(reac.values()), "Reagents": "No reagents"}
boo.append(res)
我们已经分离了所有元素,并且对于每个元素,我们调用第三方API。这会消耗太多的时间。
有没有什么方法可以减少这段时间并优化循环?
它需要大约1分钟的时间来响应。我们希望优化到5-10秒。
发布于 2020-07-31 14:39:34
只需执行此操作即可。我更改了输出的格式,因为它使事情变得不必要地复杂,并删除了您正在做的许多非pythonic的事情。你的第二次运行应该是瞬间的,如果你在方程式或反应的侧面有重复的值,第一次应该会快得多。
# pip install cachetools diskcache
from cachetools import cached
from diskcache import Cache
BASE_URL = "https://ai.chemistryinthecloud.com/smilies/"
CACHEDIR = "api_cache"
@cached(cache=Cache(CACHEDIR))
def get_similies(value):
return requests.get(BASE_URL + value).json()
def parse_eq(eq):
reac, _, reag = (set(v.split(".")) for v in eq.partition(">"))
return {
"reactants": {i: get_similies(i) for i in reac},
"reagents": {i: get_similies(i) for i in reag}
}
result = [parse_eq(eq) for eq in eqs]
https://stackoverflow.com/questions/63166887
复制相似问题