Python比较两个字符串的差异 [英] Python comparing two strings to differences
本文介绍了Python比较两个字符串的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有两个列表:
str1 = ['test1.jpg', 'test2.jpg', 'test3.jpg']
str2 = ['test1.jpg', 'test2.jpg']
您可能会注意到,str2中缺少test3.jpg.有什么办法可以将str2与str1进行比较并找到缺失的片段?
As you may well notice, test3.jpg is missing from str2. Is there a way I can compare str2 with str1 and find the missing pieces?
推荐答案
您可以使用内置类型 set
str1 = ['test1.jpg', 'test2.jpg', 'test3.jpg']
str2 = ['test1.jpg', 'test2.jpg']
s1 = set(str1)
s2 = set(str2)
print(s1-s2)
您可以从那里轻松创建函数:
From there you can easily create function:
def difference(list1,list2):
return set(list1)-set(list2)
如果您要在两者之间建立差异,请执行以下操作:对于数据:
If you want to create difference between both of them you can do the following: For data :
str1 = ['test1.jpg', 'test2.jpg', 'test3.jpg']
str2 = ['test1.jpg', 'test2.jpg', 'test4.jpg']
功能将是:
def difference(list1,list2):
return (set(list1)-set(list2)) | (set(list2)-set(list1))
或:
def difference(list1,list2):
return set(list1).symmetric_difference(set(list2))
输出:
{'test3.jpg','test4.jpg'}
{'test3.jpg', 'test4.jpg'}
此处记录了所有内容: Python3
All is documented here: Python3 Python2
这篇关于Python比较两个字符串的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文