[PYTHON]python中比较两个list的区别与共同项

在Python中,查找两个list中共同项,或者区别项,可以通过set(集合)来完成。
set中包含现成的比较方法.difference与.intersection

假设两个list为list1,list2,先将两个list转为set:
s_list1=set(list1)
s_list2=set(list2)
s_list1.difference(s_list2)表示返回list1中与list2不同的item的list
s_list1.intersection(s_list2)表示返回list1与list2中相同的item的list

以下程序为例:

list1=[‘apple’, ‘banana’,’peach’,’watermelon’]
list2=[‘strawberry’, ‘watermelon’]

s_list1=set(list1)
s_list2=set(list2)
print(“s_list1=”, end=”)
print(s_list1)
print(“s_list2=”, end=”)
print(s_list2)

print(“Items in s_list1 DIFFERENT from items in s_list2 are:”)
out = s_list1.difference(s_list2)
print(out)
print(“Items in s_list2 DIFFERENT from items in s_list1 are:”)
out = s_list2.difference(s_list1)
print(out)

print(“Items in s_list1 SAME with items in s_list1 are:”)
out = s_list1.intersection(s_list2)
print(out)

—————————————–结果为—————–

s_list1={‘apple’, ‘banana’, ‘peach’, ‘watermelon’}
s_list2={‘watermelon’, ‘strawberry’}
Items in s_list1 DIFFERENT from items in s_list2 are:
{‘apple’, ‘banana’, ‘peach’}
Items in s_list2 DIFFERENT from items in s_list1 are:
{‘strawberry’}
Items in s_list1 SAME with items in s_list1 are:
{‘watermelon’}

发表评论

邮箱地址不会被公开。 必填项已用*标注