在Python中,字符串去重意味着移除字符串中重复的字符,只保留每个字符的一个实例。以下是一些常用的字符串去重方法:
1. 使用集合(Set)
集合是一个无序的、不包含重复元素的集合。将字符串转换为集合可以自动去除重复的字符。
def remove_duplicates(s):
return ''.join(set(s))
string = "aabbccdd"
unique_string = remove_duplicates(string)
print(unique_string) # 输出: abcd
这种方法简单高效,但需要注意的是,它会丢失原始字符串中字符的顺序。
2. 使用字典(从Python 3.7起保持插入顺序)
从Python 3.7开始,字典保持插入顺序。我们可以利用这个特性来去重同时保持字符顺序。
def remove_duplicates_order_preserved(s):
return ''.join(dict.fromkeys(s))
string = "aabbccdd"
unique_string = remove_duplicates_order_preserved(string)
print(unique_string) # 输出: abcd
3. 使用列表和循环
我们可以通过遍历字符串,将每个字符添加到一个列表中,如果字符不在列表中,则添加它。
def remove_duplicates_loop(s):
unique_chars = []
for char in s:
if char not in unique_chars:
unique_chars.append(char)
return ''.join(unique_chars)
string = "aabbccdd"
unique_string = remove_duplicates_loop(string)
print(unique_string) # 输出: abcd
这种方法保留了字符的顺序,但在长字符串上可能不如集合方法高效。
4. 使用OrderedDict(Python 3.1至3.6)
在Python 3.1至3.6版本中,可以使用collections.OrderedDict
来保持字符顺序。
from collections import OrderedDict
def remove_duplicates_ordered_dict(s):
return ''.join(OrderedDict.fromkeys(s))
string = "aabbccdd"
unique_string = remove_duplicates_ordered_dict(string)
print(unique_string) # 输出: abcd
总结
- 使用集合(Set):简单高效,但会丢失顺序。
- 使用字典(Python 3.7+):去重并保持顺序。
- 使用列表和循环:去重并保持顺序,但可能效率较低。
- 使用OrderedDict(Python 3.1至3.6):去重并保持顺序。
根据需要保留字符顺序以及Python版本的不同,可以选择不同的方法来实现字符串去重。
实操
s = 'helloworldhelloworldhelloworld'
# (1)字符串拼接及not in
new_s = ''
for item in s:
if item not in new_s:
new_s += item # 拼接操作
print(new_s)
# (2)使用索引+not in
new_s2 = ''
for i in range(len(s)):
if s[i] not in new_s2:
new_s2 += s[i]
print(new_s2)
# (3)通过集合去重+列表排序(因为集合自带互异性,自动去重,只需排序)
new_s3 = set(s)
lst = list(new_s3)
lst.sort(key=s.index)
print(''.join(lst))