หากต้องการลบรายการที่ซ้ำกันทั้งหมดออกจากสตริงใน 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']