在 Python 中删除给定字符串中的所有重复项
要在 python 中删除字符串中的所有重复项,我们首先需要按空格拆分字符串,以便将每个单词放在一个数组中。然后有多种方法可以删除重复项。
我们可以先将所有单词转换为小写,然后对其进行排序,最后只选择唯一的单词来删除重复项。例如,
示例
sent = "Hi my name is John Doe John Doe is my name" # Seperate out each word words = sent.split(" ") # Convert all words to lowercase words = map(lambda x:x.lower(), words) # Sort the words in order words.sort() unique = [] total_words = len(words) i = 0 while i < (total_words - 1): while i < total_words and words[i] == words[i + 1]: i += 1 unique.append(words[i]) i += 1 print(unique)
输出
这会产生以下输出 −
['doe', 'hi', 'john', 'is', 'my']
广告内容