python找出两个列表不同元素_python 找出两个列表的相同元素与不同元素
python 找出两个列表的相同元素与不同元素,用了以下几种方法
1. 通过set 集合
list1 = [1,2,3]
list2=[2,3,4]
set1 = set(list1)
set2 = set(list2)
print(set1&set2)
{2, 3}
print(set1^set2)
{1, 4}
2.利用for循环
'''
找出两个列表中的相同元素和不同元素。
'''
def find_diff_intwo_list(list1,list2):
'''
:param list1: 列表1
:param list2: 列表2
:return:
'''
same,diff=[],[]
seq=list(set(list2))
for i in list(set(list1)):
if i not in list2:
diff.append(i)
else:
same.append(i)
for j in same:
seq.remove(j)
print("same is {},diff is {}".format(same,diff+seq))
3.利用collections集合里的方法
def find_diff_by_twolist(list1,list2):
'''
:param list1: 列表1
:param list2: 列表2
:return:
'''
from collections import Counter
newli=list(set(list1)) + list(set(list2))
count=Counter(newli)
same, diff = [], []
for i in count.keys():
if(count.get(i)>=2):
same.append(i)
else:
diff.append(i)
print("same is {},diff is {}".format(same, diff))
if __name__ == '__main__':
find_diff_intwo_list([1,2,3,5,7,7,7,98],[93,0,2,6,7,98])
find_diff_by_twolist([1,2,3,5,7,7,7,98],[93,0,2,6,7,98])