通过遍历生成器对象构建列表的最快方法

2024-05-18 11:05:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pythongitlab获取一个gitlab项目列表,这些项目作为生成器以100个为一批返回。如果一个项目有一个“snow”标记,我想把它添加到一个列表中,这个列表将被转换成一个json对象。下面是我的代码:

gl_prj_list = gl_conn.projects.list(as_list=False)

    for p in gl_prj_list:
        if "snow" in p.tag_list:
          prj = {"id": p.id}
          prj["name"] = p.path_with_namespace
          gl_data.append(prj)

    return json.dumps(gl_data), 200, {'Content-Type': 'text/plain'}

因此,最终我想要的结果可能是这样的:(100个项目中只有2个有snow标签)

[{"id": 7077, "name": "robr/snow-cli"}, {"id": 4995, "name": "test/prod-deploy-iaas-spring-starter"}]

这工作正常,但似乎有点慢。响应时间通常在3.5-5秒之间。由于我将要做这10-20批次,我想提高响应时间。你知道吗

有没有更好的方法来检查生成器的tag\u list属性中的“snow”值并返回结果?你知道吗


Tags: 项目nameinidjson列表datatag
1条回答
网友
1楼 · 发布于 2024-05-18 11:05:48

假设瓶颈不是API调用,您可以使用multiprocessing.Pool()来实现这一点。你知道吗

from multiprocessing import Pool

def f(p):
    if "snow" in p.tag_list:
        return {"id":p.id, "name":p.path_with_namespace}
    return False

gl_prj_list = gl_conn.projects.list(as_list=False)

with Pool(10) as pool: #10 processes in parallel (change this with the number of cores you have available)
    gl_data = pool.map(f, gl_prj_list)

gl_data = [i for i in gl_data if i] #get rid of the False items

json.dumps(gl_data), 200, {'Content-Type': 'text/plain'}

如果瓶颈是API调用,并且您想多次调用API,那么将调用添加到f()中并使用相同的技巧。您将并行调用API 10次,而不是按顺序调用。你知道吗

相关问题 更多 >