PyQt邮件统计功能中Counter变量无法正常累加计数问题排查
问题根因
- 你把
counter = 0这行代码写在了遍历邮件的for循环内部,每次循环处理一封新邮件的时候,都会把计数器重置为0,所以最终的数值只会等于最后一封邮件的判定结果:匹配到就加1变成1,没匹配到就保持0。 - 额外还有两个可优化的点:
- 直接把
cursor.fetchall()的结果转成字符串判断存在性效率极低,建议转成集合做存在判断,逻辑更严谨速度也更快 - 处理
currentklant的时候直接操作查询结果比替换特殊字符更可靠,避免字符串处理出错
- 直接把
修复后代码参考
@pyqtSlot(str, str) def checkaantalmail(self, email, wachtwoord): cursor.execute("SELECT DISTINCT Naam FROM Klant") # 改成集合存储,方便后续快速判断存在性 updatedklant = set(item[0] for item in cursor.fetchall()) credentials = Credentials(email, wachtwoord) acc = Account(email, credentials=credentials, autodiscover=True) # 计数器初始化移到for循环外部 counter = 0 for item in acc.inbox.all().order_by('-datetime_received')[:500]: inboxmail = str(item.sender).split("'") currentinboxmail = inboxmail[3] cursor.execute("SELECT DISTINCT Klant FROM Mail WHERE Mail=?", currentinboxmail) # 直接取查询结果的第一个字段,不需要转字符串再替换特殊字符 res = cursor.fetchone() if not res: continue currentklant = res[0] if currentklant not in updatedklant: print("yes") print(currentklant) counter += 1 print("total", counter)
内容的提问来源于stack exchange,提问作者Minimumspace
相关产品推荐
相关产品推荐

