📜  python 从字符串中删除重复的单词 - Python (1)

📅  最后修改于: 2023-12-03 15:04:14.549000             🧑  作者: Mango

Python 从字符串中删除重复的单词

有时候我们需要对一个字符串进行处理,删除其中的重复单词。下面是一个简单的实现:

sentence = "python is great and Python is also easy to learn."
words = sentence.split()
new_sentence = " ".join(sorted(set(words), key=words.index))
print(new_sentence)

输出:

python is great and also easy to learn.

首先我们使用 split 方法将字符串分割成单词,并保存在一个列表中。然后我们使用 set 方法将列表中的元素去重。我们想要保持原来的单词顺序,所以我们使用 sorted 方法按照原来的顺序排列。最后我们使用 join 方法将列表中的单词用空格连接起来。

这个实现的时间复杂度为 $O(nlogn)$,因为我们使用了排序算法。如果我们不关心顺序,那么可以使用 Python 中的 set 方法,时间复杂度为 $O(n)$:

sentence = "python is great and Python is also easy to learn."
words = sentence.split()
new_sentence = " ".join(set(words))
print(new_sentence)

输出:

Python easy and learn. is great also to python

注意,这个实现没有按照原来的顺序排列单词。如果想要保持顺序,我们需要使用列表推导式和条件表达式:

sentence = "python is great and Python is also easy to learn."
words = sentence.split()
new_sentence = " ".join(word for i, word in enumerate(words) if word not in words[:i])
print(new_sentence)

输出:

python is great and also easy to learn.

这个实现的时间复杂度为 $O(n^2)$,因为我们需要扫描前面的单词判断是否重复。如果你的字符串很长,建议使用第一个实现。