Python 程序删除两个字符串中共同的单词

pythonserver side programmingprogramming更新于 2025/11/9 9:48:17

当需要删除两个字符串中共同的单词时,会定义一个方法,该方法接受两个字符串。根据空格拆分字符串,并使用列表推导来过滤结果。

示例

下面是相同的演示

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("结果为:")
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。

  • 在方法外部,定义了两个字符串并显示在控制台上。

  • 通过传递所需参数来调用该方法。

  • 输出显示在控制台上。


相关文章


有用资源