简体   繁体   English

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

[英]list index out of range error python 2.7

I'm creating a bunch of lists that looks like this: 我正在创建一堆看起来像这样的列表:

[ObjectId('542de00c763f4a7f558be1cf')]
[ObjectId('545284e7bf2e4ea2778b479d'), ObjectId('542de00c763f4a7f558be1d1')]
...etc

All of them have at least one item. 他们所有人都有至少一项。 When I run this loop, however: 但是,当我运行此循环时:

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]

I get: 我得到:

    print "temp_list[0] is", temp_list[0]
IndexError: list index out of range

If I comment out print "temp_list[1] is", temp_list[0] I get: 如果我注释掉print "temp_list[1] is", temp_list[0]得到:

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

Why am I getting the error? 为什么会出现错误?

Since it's a loop, I'm assuming that at one point your query returns an empty list for a given agent_id which crashes the script at temp_list[0] since it's empty. 由于这是一个循环,因此我假设您的查询在某一时刻针对给定的agent_id返回一个空列表,由于该脚本为空,因此该脚本使temp_list[0]崩溃。

off topic mongo's distinct returns a list so there's no need to loop through it and append it to another list (unless you have a good reason to do so). 题外话蒙戈的distinct回报的列表,以便有通过它无需环路并将其追加到另一个列表(除非你有一个很好的理由这样做)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM