python学习——字符串的去重

在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))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Qhumaing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值