簡體   English   中英

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列表中的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')

也許您應該嘗試以下操作(如果我理解正確的話)。 我們像以前一樣增加計數變量,但只打印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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM