当需要删除两个字符串中共同的单词时,定义了一个接受两个字符串的方法。字符串是基于空格吐出的,列表理解用于过滤结果。
下面是相同的演示
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("第一个字符串是:") print(my_string_1) my_string_2 = "Python is fun to learn" print("第二个字符串是:") print(my_string_2) print("结果是:") print(common_words_filter(my_string_1, my_string_2))输出结果
第一个字符串是: Python is fun 第二个字符串是: Python is fun to learn The uncommon words from the two strings are : ['to', 'learn']
定义了一个名为“common_words_filter”的方法,它接受两个字符串作为参数。
定义了一个空字典,
第一个字符串基于空格分割并迭代。
'get' 方法用于获取单词和特定索引。
第二个字符串也是如此。
列表推导用于遍历字典并检查字数是否为 1。
在该方法之外,定义了两个字符串并显示在控制台上。
通过传递所需的参数来调用该方法。
输出显示在控制台上。