gpt4 book ai didi

python - 索引错误: list index out of range (in query results)

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:24 24 4
gpt4 key购买 nike

我在理解如何使用查询结果时遇到问题。我问了大约六个问题,但我仍然不明白。我从以前的代码中复制并使其以某种方式工作,但由于我不理解基本概念,如果我进行微小的更改,代码就会崩溃。如果您能告诉我您如何想象这里发生的事情并向我解释,我将非常感激。谢谢。

class ReceiveEmail(InboundMailHandler):
def receive(self, message):
logging.info("Received email from %s" % message.sender)
plaintext = message.bodies(content_type='text/plain')
for text in plaintext:
txtmsg = ""
txtmsg = text[1].decode()
logging.info("Body is %s" % txtmsg)
logging.info("CC email is %s" % ((message.cc).split(",")[1]))

query = User.all()
query.filter("userEmail =", ((message.cc).split(",")[1]))
results = query.fetch(1)

for result in results:
result.userScore += 1

um = results[0]
um.userScore = result.userScore
um.put()

在这段代码中,据我了解,查询从抄送列表中获取第二个电子邮件地址并获取结果。

然后我将 userScore 加 1。

接下来,我想更新数据存储中的此项,所以我说

        um = results[0]                            
um.userScore = result.userScore
um.put()

但这会给出索引超出范围的错误:

um = results[0]
IndexError: list index out of range
为什么?我想象 results[0] 是结果的第零项。为什么超出范围?我唯一能想到的是,该列表可能是 None。但我不明白为什么。它必须具有已获取的 1 项。

此外,如果我尝试通过将索引从 [1] 更改为 [0] 来测试第一个电子邮件地址

query.filter("userEmail =",  ((message.cc).split(",")[0]))

然后我没有得到IndexError

我在这里做错了什么?

谢谢!

编辑

查看评论:

(message.cc).split(",")[0]) 

在电子邮件前面留了一个空格(从第二封电子邮件开始),因此查询与它们不匹配;

>>> cc.split(",")
['cc12@example.com', ' cc13@example.com', ' cc13@example.com']

在逗号后添加空格解决了问题:

>>> listcc = cc.split(", ")
>>> listcc
['cc12@example.com', 'cc13@example.com', 'cc13@example.com']
>>>

最佳答案

要理解代码,请将其分解并逐段查看:

class ReceiveEmail(InboundMailHandler):
def receive(self, message):
logging.info("Received email from %s" % message.sender)

# Get a list of CC addresses. This is basically a for loop.
cc_addresses = [address.strip() for address in message.cc.split(",")]
# The CC list goes with the message, not the bodies.
logging.info("CC email is %s" % (cc_addresses))

# Get and iterate over all of the *plain-text* bodies in the email.
plaintext = message.bodies(content_type='text/plain')
for text in plaintext:
txtmsg = ""
txtmsg = text[1].decode()
logging.info("Body is %s" % txtmsg)

# Setup a query object.
query = User.all()
# Filter the user objects to get only the emails in the CC list.
query.filter("userEmail IN", cc_addresses)
# But, only get at most 10 users.
users = query.fetch(10)

logging.info('Got %d user entities from the datastore.' % len(users))

# Iterate over each of the users increasing their score by one.
for user in users:
user.userScore += 1

# Now, write the users back to the datastore.
db.put(users)
logging.info('Wrote %d user entities.' % len(users))

我会对您的模型结构进行调整。当您创建用户实体时,我会将 key_name 设置为电子邮件地址。您将能够使查询更加高效。

一些引用:

关于python - 索引错误: list index out of range (in query results),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4236427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com