【问题标题】:Removing a word from a list从列表中删除单词
【发布时间】:2021-12-29 04:41:18
【问题描述】:

所以我得到了一个包含名称的列表,我正在尝试从列表中删除这些名称。但不知何故,它并没有按照我想要的方式工作。任何帮助将非常感激。我认为问题出在替换功能上,但我不确定。

功能:

@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 = str(cursor.fetchall())
    
    test = updatedklant

    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 = str(cursor.fetchall())

        remove_characters = ["(",")",",","]","["]
        for characters in remove_characters:
            currentklant = currentklant.replace(characters, "")

        if currentklant not in updatedklant:

            for idx, elem in enumerate(test):
                if elem[0] == currentklant:
                    test.pop(idx)

现在打印这个:

currentklant == 'alerttesting'

test == [('alerttestting', ), ('emretestingsystems', ), ('jarnodebaas', ),('yikes', )]

结果应该是:

currentklant == 'alerttesting'

test ==[('emretestingsystems', ), ('jarnodebaas', ),('yikes', )]

【问题讨论】:

    标签: python exchangewebservices


    【解决方案1】:

    永远不要将cursor.fetchall() 的结果转换为str,然后去掉你不喜欢的字符。这将是一个巨大的麻烦来源。如果名称本身包含这些字符之一,例如"Bond, James""O'Brien",该怎么办?

    将其保存为 Python 对象(可能是列表或元组)并以该形式对其进行处理。

    在这种情况下,您可能想要这样的东西:

        ...
        updatedklant = cursor.fetchall()  # No more str()
        ...
                currentklant = cursor.fetchall())  # No more str()
                ...
                test = [klant for klant in updatedklant if klant != currentklant]
    

    【讨论】:

    • 感谢您的提示,我会牢记这一点并在我的程序中使用它
    【解决方案2】:

    应该可以正常工作

    [('alerttestting',), ('emretestingsystems',), ('jarnodebaas',), ('yikes',)]

    if __name__ == "__main__":
        currentklant = 'alerttestting'
        test = [('alerttestting',), ('emretestingsystems',), ('jarnodebaas',), ('yikes',)]
        for idx, elem in enumerate(test):
            if elem[0] == currentklant:
                test.pop(idx)
    

    [('emretestingsystems',), ('jarnodebaas',), ('yikes',)]

    【讨论】:

    • 我会试试这个
    • 当变量 currentklant 和 test 被硬编码时,这不是我正在寻找的解决方案。但它从数据库中获取信息,所以我尝试做类似 test = test.我将更新主代码,以便您可以看到我现在拥有的内容。
    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多