Python 循环不遍历列表
Python loop not iterating through the list
我有这段代码,我试图在其中循环遍历列表中具有指定电子邮件地址的邮箱,但我得到的是所有电子邮件地址的输出。当我打印计数时,我得到大约 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')
如 所述,如果仅获取发件人,您可以获得更好的性能:
account.inbox.all().order_by('-datetime_received').only('sender')
也许您应该尝试以下操作(如果我理解正确的话)。我们像以前一样增加计数变量,但只打印 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])
我有这段代码,我试图在其中循环遍历列表中具有指定电子邮件地址的邮箱,但我得到的是所有电子邮件地址的输出。当我打印计数时,我得到大约 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')
如
account.inbox.all().order_by('-datetime_received').only('sender')
也许您应该尝试以下操作(如果我理解正确的话)。我们像以前一样增加计数变量,但只打印 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])