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("第一个字符串是:")
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。
在该方法之外,定义了两个字符串并显示在控制台上。
通过传递所需的参数来调用该方法。
输出显示在控制台上。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下