[英]how to get value exists in two separate lists using python
Compare two lists and find duplicate that exist in both lists from two lists remove the existing duplicates and create new lists.比较两个列表并从两个列表中找到两个列表中存在的重复项删除现有重复项并创建新列表。
Input
a= [
"DJI_0229.jpg",
"DJI_0232.jpg",
"DJI_0233.jpg"
"DJI_0235.jpg"
]
b= [
"DJI_0229.jpg",
"DJI_0232.jpg",
"DJI_0233.jpg"
"DJI_0230.jpg",
"DJI_0231.jpg",
"DJI_0234.jpg"
]
output =
[
"DJI_0230.jpg",
"DJI_0231.jpg",
"DJI_0234.jpg",
"DJI_0235.jpg"
]
you can use this你可以用这个
def remove_dupilicate(List1,List2):
return [item for item in List1 if item not in List2]
new_a = remove_dupilicate(a, b)
new_b = remove_dupilicate(b, a)
print(new_a,new_b)
output for new_a list is ['DJI_0235.jpg']
and new_b list is ['DJI_0230.jpg', 'DJI_0231.jpg', 'DJI_0234.jpg']
new_a 列表的输出是
['DJI_0235.jpg']
和 new_b 列表是['DJI_0230.jpg', 'DJI_0231.jpg', 'DJI_0234.jpg']
you can do this你可以这样做
a= ["DJI_0229.jpg","DJI_0232.jpg","DJI_0233.jpg","DJI_0235.jpg"]
b= ["DJI_0229.jpg","DJI_0232.jpg","DJI_0233.jpg","DJI_0230.jpg","DJI_0231.jpg","DJI_0234.jpg"]
c = []
for image in (a+b):
if image not in c:
c.append(image)
else:
c.remove(image)
print(c)
The most simplest way to achieve what you want is using symmetric difference of sets.实现您想要的最简单的方法是使用集合的对称差异。 Consider the below venn diagram :
考虑下面的维恩图:
Code implementation代码实现
from pprint import pprint
a = ["DJI_0229.jpg", "DJI_0232.jpg", "DJI_0233.jpg", "DJI_0235.jpg"]
b = [
"DJI_0229.jpg",
"DJI_0232.jpg",
"DJI_0233.jpg",
"DJI_0230.jpg",
"DJI_0231.jpg",
"DJI_0234.jpg",
]
final_list = sorted(
list(
set(a).symmetric_difference(set(b)) # Using some maths :-)
) # Converting the set to list
) # Sorting the resultant list
pprint(final_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.