如何从字符串中删除所有重复的字符?
例如:
例如:
Input: string = 'Hello'
Output: 'Heo'
这个问题与从字符串中移除重复字符的问题不同,因为我不想打印出重复的字符,而是想删除它们。
Input: string = 'Hello'
Output: 'Heo'
这个问题与从字符串中移除重复字符的问题不同,因为我不想打印出重复的字符,而是想删除它们。
join
函数,例如:>>> x = 'Hello'
>>> ''.join(c for c in x if x.count(c) == 1)
'Heo'
O(n**2)
。 - yatuO(n**2)
,最坏情况下是 O(nm)
:) - han solo计数器
,并且通过在计数器中查找仅出现一次的元素来检索它们:from collections import Counter
c = Counter(string)
''.join([i for i in string if c[i]==1])
# 'Heo'
list
以进行连接。对此感到抱歉 :) - han soloa = 'Hello'
list_a = list(a)
output = []
for i in list_a:
if list_a.count(i) == 1:
output.append(i)
''.join(output)
filter
:s = 'Hello'
result = ''.join(filter(lambda c: s.count(c) == 1, s))
# result - Heo
import re
print(re.sub(r"(.)\1+", "", "hello")) # result = heo
print(re.sub(r"(.)\1+", "", "helloo")) # result = he
print(re.sub(r"(.)\1+", "", "hellooo")) # result = he
print(re.sub(r"(.)\1+", "", "sports")) # result = sports
prog = re.compile(r"(.)\1+")
print(prog.sub("", "hello"))
为了限制在某些字符子集中搜索重复字母,您可以相应地调整正则表达式。
print(re.sub(r"(\S)\1+", "", "hello")) # Search duplicated non-whitespace chars
print(re.sub(r"([a-z])\1+", "", "hello")) # Search for duplicated lowercase letters
或者,使用列表推导的方法可以如下所示:
from itertools import groupby
dedup = lambda s: "".join([i for i, g in groupby(s) if len(list(g))==1])
print(dedup("hello")) # result = heo
print(dedup("helloo")) # result = he
print(dedup("hellooo")) # result = he
print(dedup("sports")) # result = sports
注意,使用正则表达式的第一种方法在我的电脑上比第二种方法快8-10倍。(系统:Python 3.6.7,MacBook Pro(2015年中期))