如何从字符串中删除重复的字符?

Edd*_*yIT -1 python list python-3.x

如何从字符串中删除所有重复的字符?

例如:

Input:  string = 'Hello'
Output: 'Heo'
Run Code Online (Sandbox Code Playgroud)

与从字符串中删除重复字符不同的问题,因为我不想打印出重复项,但我想删除它们。

han*_*olo 6

您可以使用generator表达式,join例如

>>> x = 'Hello'
>>> ''.join(c for c in x if x.count(c) == 1)
'Heo'
Run Code Online (Sandbox Code Playgroud)

  • 不必要是`O(n ** 2)` (2认同)

yat*_*atu 5

您可以从字符串构造 a Counter,并从中检索在计数器中仅出现一次的元素:

from collections import Counter

c = Counter(string)
''.join([i for i in string if c[i]==1])
# 'Heo'
Run Code Online (Sandbox Code Playgroud)