List of all unique characters in a string?

后端 未结 7 1557
再見小時候
再見小時候 2020-11-27 18:03

I want to append characters to a string, but want to make sure all the letters in the final list are unique.

Example: \"aaabcabccd\"

7条回答
  •  渐次进展
    2020-11-27 18:31

    Use an OrderedDict. This will ensure that the order is preserved

    >>> ''.join(OrderedDict.fromkeys( "aaabcabccd").keys())
    'abcd'
    

    PS: I just timed both the OrderedDict and Set solution, and the later is faster. If order does not matter, set should be the natural solution, if Order Matter;s this is how you should do.

    >>> from timeit import Timer
    >>> t1 = Timer(stmt=stmt1, setup="from __main__ import data, OrderedDict")
    >>> t2 = Timer(stmt=stmt2, setup="from __main__ import data")
    >>> t1.timeit(number=1000)
    1.2893918431815337
    >>> t2.timeit(number=1000)
    0.0632140599081196
    

提交回复
热议问题