Python循环未遍历列表

问题描述

我有这段代码,我试图在列表中循环浏览具有指定电子邮件地址的邮箱,但我却得到了所有电子邮件地址的输出。当我打印计数时,我会得到10种不同的电子邮件地址,但不是仅限于列表中的地址。如何使其仅打印“电子邮件”列表中的那些邮件

from exchangelib import Credentials,Account
from collections import defaultdict

emails = ['test1@random.com','test2@random.com']

for email in emails:
    credentials = Credentials('hidden@hidden.com','hiddenpass')
    account = Account('hidden@hidden.com',credentials=credentials,autodiscover=True)
    counts = defaultdict(int)
    for item in account.inbox.all().order_by('-datetime_received')[:100]:
        counts[item.sender.email_address] += 1
print(counts)

解决方法

您无需在emails列表上进行迭代。如果要过滤未出现在emails列表中的电子邮件,可以执行以下操作:

for item in account.inbox.all().order_by('-datetime_received')[:100]:
    if item.sender.email_address in emails:
        counts[item.sender.email_address] += 1

我对这个库不熟悉,但是也许您可以选择仅获取与以下内容类似的相关结果:

account.inbox.all().filter(sender=email).order_by('-datetime_received')

@erikcederstrand所述,如果仅提取发件人,则可以获得更好的性能:

account.inbox.all().order_by('-datetime_received').only('sender')
,

也许您应该尝试以下操作(如果我理解正确的话)。我们像以前一样增加count变量,但仅打印emails中的变量:

credentials = Credentials('hidden@hidden.com','hiddenpass')
account = Account('hidden@hidden.com',credentials=credentials,autodiscover=True)
counts = defaultdict(int)
for item in account.inbox.all().order_by('-datetime_received')[:100]:
    counts[item.sender.email_address] += 1
    if item.sender.email_address in emails:
        print(item.sender.email_address)
        print(counts[item.sender.email_address])

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...