Python程式去除兩個字串中共同的單詞
當需要去除兩個字串中共同的單詞時,定義一個方法,該方法接收兩個字串作為引數。字串根據空格分割,並使用列表推導式過濾結果。
示例
以下是相同的演示
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。
在方法外部,定義兩個字串並在控制檯上顯示。
透過傳遞所需引數來呼叫該方法。
在控制檯上顯示輸出。
廣告