如何在python中加快for循环

如何在python中加快for循环,python,python-2.7,Python,Python 2.7,我有以下的方法,需要永远: def UuserEmailAgentIdD(self, CemailToIdD, MUuserWithAgentD): """return a dict of user_email:agent:id - only users with agents Argumetns: CemailToIdD: dict of all user emails : ids MUuser

我有以下的方法,需要永远:

def UuserEmailAgentIdD(self, CemailToIdD, MUuserWithAgentD):
    """return a dict of user_email:agent:id - only users with agents
       Argumetns:
                CemailToIdD:        dict of all user emails : ids
                MUuserWithAgentD:   dict of pure user ID:agent_id"""
    return_dict = {}
    user_ids = MUuserWithAgentD.keys() 
    for user_email in CemailToIdD:
        if CemailToIdD[user_email] in user_ids: 
            return_dict[user_email] = MUuserWithAgentD[CemailToIdD[user_email]]
    return return_dict

如何加快速度?

看起来您正在执行连接。您是否尝试过适合此任务的库?我建议您在做任何事情之前,使用探查器查看花费的时间。另外,让我们来测量时间,以便具体了解何时改进了执行时间。这样做如何:
{user:{id:MUuserWithAgentD[id]}对于用户,id在cemailtoid.items()中,如果id在MUuserWithAgentD.keys()中
这不会改变逻辑,但会使用在python中优化的列表/字典理解。永远不会,曾经在somedict.keys()中做过
事情吗。您正在执行缓慢的列表搜索,而不是快速的哈希查找。您知道您在CemailToIdD
中如何在不调用
键的情况下对用户电子邮件执行
?您可以用同样的方法测试密钥是否存在,使用d中的
东西而不是d.keys()中的
东西,它将执行哈希查找。