Python使用in和not in删除字符串中的重复项

2024-10-02 12:25:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用in和not in运算符以及累加器模式来删除字符串中的所有重复字母,并在保持顺序的同时返回一个新字符串。你知道吗

withDups = "The Quick Brown Fox Jumped Over The Lazy Dog"

def removeDups(s):
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    sWithoutDups = ""
    for eachChar in withDups:
        if eachChar in alphabet:
            sWithoutDups = eachChar + sWithoutDups
        return sWithoutDups

print(removeDups(withDups))

我当前的代码只返回字符串的第一个字母。我对python和一般的代码非常陌生,所以请原谅,如果我忽略了一些简单的东西,我当前的代码甚至不是正确的方向,或者如果我发布了一些不应该的东西。你知道吗


Tags: the字符串代码in顺序字母模式not
3条回答

你离我很近。您需要将return移到for循环之外,这是因为函数一旦遇到return语句就会返回。你还需要在移动中更新字母表,也就是说,这个字母表已经被哨兵访问过了

def removeDups(s):
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    sWithoutDups = ""
    for eachChar in withDups:
        if eachChar in alphabet:
            sWithoutDups =  sWithoutDups + eachChar 
            alphabet = alphabet.replace(eachChar,'-')  # The character has 
                                                       # already been found
    return sWithoutDups        # Move return here

输出

TheQuickBrownFxJmpdOvLazyDg

正如前面提到的below更好的方法是

if eachChar not in sWithoutDups:
    sWithoutDups =  sWithoutDups + eachChar 

这样你就不需要在字母表上有哨兵了。你知道吗

另一种方法是

def removeDups(s):    
    l = list(s)
    tmp = []
    for i in l:
        if i not in tmp and i != ' ':        
            tmp.append(i)
    tmp.remove(' ')
    return ''.join(tmp)
withDups = "The Quick Brown Fox Jumped Over The Lazy Dog"
withoutDups = ""

for letter in withDups:
    if letter not in withoutDups:
        withoutDups += letter

print withoutDups

请记住,空格也被视为字符。你知道吗

返回for循环内部,这意味着您永远不会进入循环的第二次迭代。我怀疑你想把它移到缩进的一层,所以它和for在同一层,而不是在里面

相关问题 更多 >

    热门问题