You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt开发中列表删除指定名称元素功能运行未达预期求助

核心错误点

  • 你将cursor.fetchall()返回的元组列表直接强制转成了字符串,赋值给updatedklant后又赋值给test,此时test是字符串类型,后续的遍历、取值、pop操作全部无效。
  • 判断条件逻辑写反:现有代码中仅当currentklant不存在于updatedklant时才执行删除,和你要删除存在项的需求完全相反。
  • 遍历列表的同时调用pop删除元素,会导致后续元素索引前移,出现漏删、索引越界问题。
  • 查询currentklant时不需要把fetchall结果转字符串再替换特殊字符,直接取返回结果集中的元素即可,同时注意参数化查询的传参格式要求。

修复后代码

@pyqtSlot(str, str)
def rapportmail (self, email, wachtwoord):
    credentials = Credentials(email, wachtwoord)
    acc = Account(email, credentials=credentials, autodiscover=True)

    cursor.execute("SELECT DISTINCT Naam FROM Klant")
    # 直接保留原生列表类型,不要转字符串
    updatedklant = cursor.fetchall()
    # 拷贝列表避免修改原查询结果
    test = updatedklant.copy()

    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,))
        currentklant_res = cursor.fetchone()
        # 无匹配结果直接跳过
        if not currentklant_res:
            continue
        # 直接取查询到的名称,不需要额外处理字符串
        currentklant = currentklant_res[0]

        # 存在对应名称时执行过滤删除
        if currentklant in [item[0] for item in test]:
            # 用列表推导式过滤代替遍历pop,避免索引异常
            test = [elem for elem in test if elem[0] != currentklant]

内容的提问来源于stack exchange,提问作者Minimumspace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 15:36:04