列表索引超出范围错误python 2.7

列表索引超出范围错误python 2.7,python,python-2.7,Python,Python 2.7,我正在创建一组如下所示的列表: [ObjectId('542de00c763f4a7f558be1cf')] [ObjectId('545284e7bf2e4ea2778b479d'), ObjectId('542de00c763f4a7f558be1d1')] ...etc 他们都至少有一个项目。但是,当我运行此循环时: for agent_id in agent_ids: curs_obj = user_coll_obj.find({"agent_id" : str(agent_i

我正在创建一组如下所示的列表:

[ObjectId('542de00c763f4a7f558be1cf')]
[ObjectId('545284e7bf2e4ea2778b479d'), ObjectId('542de00c763f4a7f558be1d1')]
...etc
他们都至少有一个项目。但是,当我运行此循环时:

for agent_id in agent_ids:
    curs_obj = user_coll_obj.find({"agent_id" : str(agent_id)}).distinct("_id")
    temp_list=[]
    for obj in curs_obj:
        temp_list.append(obj)
    # print len(temp_list)
    print "len(temp_list) is" , len(temp_list)
    print "temp_list is" , temp_list
    print "temp_list[0] is", temp_list[0]
我得到:

    print "temp_list[0] is", temp_list[0]
IndexError: list index out of range
如果我注释掉
打印“临时列表[1]为”,临时列表[0]
我得到:

Len(temp_list) is 2
temp_list is [ObjectId('542de00c763f4a7f558be1cb'), ObjectId('54c123d2bf2e4e140e8b45fc')]
....etc.

为什么会出现错误?

由于这是一个循环,我假设您的查询在某一点返回一个给定代理id的空列表,该列表在
临时列表[0]
处崩溃脚本,因为它是空的


非主题mongo的
distinct
返回一个列表,因此无需循环并将其附加到另一个列表中(除非您有充分的理由这样做)。

什么是
len(temp_list)
在错误发生之前打印?可能在该错误之前打印的内容会显示一个包含值的temp_列表和一个len>0,对吗?尝试添加:
如果len(临时列表)>0:
打印“临时列表[0]是”,临时列表[0]
等之前。