# 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])

• 6
点赞
• 34
收藏
觉得还不错? 一键收藏
• 0
评论

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。