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

Python Removing Duplicates in a String Using in and not in

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

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))

我当前的代码return只是字符串的第一个字母。我对 python 和一般编码还很陌生,所以如果我忽略了一些简单的东西,我当前的代码甚至不是正确的方向,或者如果我发布了不应该发布的内容,请原谅。

你 return 在 for 循环中,这意味着你永远不会进入循环的第二次迭代。我怀疑你想要移出一级缩进,所以它与 for 处于同一级别,而不是在它里面

你离得很近。您需要将 return 移到 for 循环之外,这是因为该函数一旦遇到 return 语句就会 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

提到的 更好的方法是

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

请记住,空格被视为一个字符。

让 Python 完成工作:

''.join(set(withDups))