在 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']
廣告內容