เมื่อจำเป็นต้องลบคำที่เหมือนกันในสตริงทั้งสอง จะมีการกำหนดเมธอดที่รับสองสตริง สตริงจะถ่มน้ำลายตามช่องว่างและใช้ความเข้าใจรายการเพื่อกรองผลลัพธ์ออก
ตัวอย่าง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน
def common_words_filter(my_string_1, my_string_2):
my_word_count = {}
for word in my_string_1.split():
my_word_count[word] = my_word_count.get(word, 0) + 1
for word in my_string_2.split():
my_word_count[word] = my_word_count.get(word, 0) + 1
return [word for word in my_word_count if my_word_count[word] == 1]
my_string_1 = "Python is fun"
print("The first string is :")
print(my_string_1)
my_string_2 = "Python is fun to learn"
print("The second string is :")
print(my_string_2)
print("The result is :")
print(common_words_filter(my_string_1, my_string_2)) ผลลัพธ์
The first string is : Python is fun The second string is : Python is fun to learn The uncommon words from the two strings are : ['to', 'learn']
คำอธิบาย
-
มีการกำหนดเมธอดชื่อ 'common_words_filter' ซึ่งรับสองสตริงเป็นพารามิเตอร์
-
มีการกำหนดพจนานุกรมว่าง
-
สตริงแรกจะถูกแบ่งตามช่องว่างและวนซ้ำ
-
วิธี 'get' ใช้เพื่อรับคำและดัชนีเฉพาะ
-
เช่นเดียวกันสำหรับสตริงที่สอง
-
ความเข้าใจรายการจะใช้เพื่อทำซ้ำผ่านพจนานุกรมและตรวจสอบว่าจำนวนคำเป็น 1 หรือไม่
-
นอกเมธอด จะมีการกำหนดสตริงสองสตริงและแสดงบนคอนโซล
-
วิธีการนี้ถูกเรียกโดยการส่งผ่านพารามิเตอร์ที่จำเป็น
-
เอาต์พุตจะแสดงบนคอนโซล