Python Comparing Two Strings To Differences
I currently have two lists: str1 = ['test1.jpg', 'test2.jpg', 'test3.jpg'] str2 = ['test1.jpg', 'test2.jpg'] As you may well notice, test3.jpg is missing from str2. Is there a way
Solution 1:
well. those are actually 2 list of strings you got there. One simple way to compare 'em would be to:
missing=[x for x in str1 if x not in str2]missing
Out:
['test3.jpg']
hope that helps!
Solution 2:
The solution using Set difference operator:
str1 = ['test1.jpg', 'test2.jpg', 'test3.jpg']
str2 = ['test1.jpg', 'test2.jpg']
diff = list(set(str1) - set(str2))
# the same can be achieved with set.difference(*others) method:# diff = list(set(str1).difference(set(str2))) print(diff)
The output:
['test3.jpg']
https://docs.python.org/3/library/stdtypes.html?highlight=set#set.difference
Solution 3:
You can use built-in type 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:
defdifference(list1,list2):
returnset(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']
Funcion would be:
defdifference(list1,list2):
return (set(list1)-set(list2)) | (set(list2)-set(list1))
Or :
defdifference(list1,list2):
returnset(list1).symmetric_difference(set(list2))
Outputs:
{'test3.jpg', 'test4.jpg'}
Post a Comment for "Python Comparing Two Strings To Differences"