Khi cần xóa từ chung trong hai chuỗi, ta định nghĩa phương thức nhận hai chuỗi. Tách chuỗi theo khoảng trắng và dùng list comprehension lọc kết quả.
Ví dụ
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))
Đầu ra
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']
Giải thích
- Hàm
common_words_filternhận hai chuỗi. - Dictionary rỗng đếm từ.
- Tách chuỗi 1 theo space, lặp, dùng
getđếm. - Làm tương tự chuỗi 2.
- List comprehension lọc từ có count = 1 (chỉ xuất hiện ở một chuỗi).