在 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']
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP