Python 索引错误:列表索引超出范围
我遇到了一个错误,叫做 IndexError: list index out of range。这个错误是因为我在处理消息的收件人列表时出了问题。我已经把每条消息的收件人列表合并成了一个单一的列表。请问我该怎么解决这个问题呢?
import json
import pymongo # pip install pymongo
from bson import json_util # Comes with pymongo
import re
from pymongo import MongoClient
# The basis of our query
FROM = "kenneth.lay@enron.com"
client = pymongo.MongoClient('mongodb://user:user123@ds033499.mongolab.com:33499/enron')
db = client.enron
mbox = db.mbox
# Get the recipient lists for each message
recipients_per_message = db.mbox.aggregate([
{"$match" : {"From" : re.compile(r".*{0}.*".format(FROM), re.IGNORECASE)}},
{"$project" : {"From" : 1, "To" : 1} },
{"$group" : {"_id" : "$From", "recipients" : {"$addToSet" : "$To" } } }
])['result'][0]['recipients']
# Collapse the lists of recipients into a single list
all_recipients = [recipient
for message in recipients_per_message
for recipient in message]
# Calculate the number of recipients per sent message and sort
recipients_per_message_totals = \
sorted([len(recipients)
for recipients in recipients_per_message])
# Demonstrate how to use $unwind followed by $group to collapse
# the recipient lists into a single list (with no duplicates
# per the $addToSet operator)
unique_recipients = db.mbox.aggregate([
{"$match" : {"From" : re.compile(r".*{0}.*".format(FROM), re.IGNORECASE)}},
{"$project" : {"From" : 1, "To" : 1} },
{"$unwind" : "$To"},
{"$group" : {"_id" : "From", "recipients" : {"$addToSet" : "$To"}} }
]['result'][0]['recipients'])
print all_recipients
print "Num total recipients on all messages:", len(all_recipients)
print "Num recipients for each message:", recipients_per_message_totals
print "Num unique recipients", len(unique_recipients)
这是错误的详细信息
IndexError Traceback (most recent call last)
<ipython-input-85-b1e01d6382fb> in <module>()
18 {"$project" : {"From" : 1, "To" : 1} },
19 {"$group" : {"_id" : "$From", "recipients" : {"$addToSet" : "$To" } } }
--->20 ])['result'][0]['recipients']
21
22 # Collapse the lists of recipients into a single list
IndexError: list index out of range
1 个回答
0
其实,改变这个:
{"$match" : {"From" : {"$regex": "^" + FROM, "$options": "i"} }},
这是你的卡片吗?
如果是的话,看起来你是在尝试把一个真正的正则表达式放进MongoDB想要的字符串里。所以才会有这样的形式。
附言:去掉不区分大小写的匹配。这没什么用,因为你的整个集合都会被扫描。与其这样,不如把你集合里的所有邮箱地址都存成小写。邮箱本身不区分大小写。把你的存储和输入都变成小写,这样一切都会运行得更快。