【问题标题】:How remove duplicate letters in a string [duplicate]如何删除字符串中的重复字母[重复]
【发布时间】:2013-10-28 09:44:11
【问题描述】:

有没有办法删除重复的字符?例如,如果我们输入“hello”,输出将是“helo”;另一个例子是“溢出”,输出将是“溢出”;另一个示例“段落”,输出将是“parghs”。

我试过了

def removeDupes(mystring):
    newStr = ""
    for ch in string:
        if ch not in newStr:
            newStr = newStr + ch
    return newStr

【问题讨论】:

  • 那段代码有什么问题? — 顺便说一下,参数称为mystring,但您在for 循环中使用string

标签: python


【解决方案1】:

string 更改为mystring

def removeDupes(mystring):
    newStr = ""
    for ch in mystring:
        if ch not in newStr:
            newStr = newStr + ch
    return newStr

print removeDupes("hello")
print removeDupes("overflow")
print removeDupes("paragraphs")

>>> 
helo
overflw
parghs

【讨论】:

    【解决方案2】:

    是的,有一个叫做集合的东西:

    unique = set()
    
    [ unique.add(c) for c in 'stringstring' ]
    

    【讨论】:

    • 这不会保留顺序,如果这对 OP 很重要
    • 另外,set(x for x in 'stringstring') 不是更好,更 Pythonic 吗?
    【解决方案3】:

    我会为此使用collections.OrderedDict

    >>> from collections import OrderedDict
    >>> data = "paragraphs"
    >>> print "".join(OrderedDict.fromkeys(data))
    parghs
    

    【讨论】:

    • -1 抄袭this answer
    • @Doorkob 我不知道这个答案——我就是这样做的。
    • 好吧,我只是假设这里是真诚的,相信你。无论如何,这是一个重复的问题
    • 你是对的,它是。标记它!
    猜你喜欢
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2015-06-07
    • 1970-01-01
    相关资源
    最近更新 更多