小猿会从最基础的面试题开始,每天一题。如果参考答案不够好,或者有错误的话,麻烦大家可以在留言区给出自己的意见和讨论,大家是要一起学习的 。
废话不多说,开始今天的题目:
问:简单Python求列表的差集、交集与并集?
答:先来说说这三者的定义,读过初中数学的应该都知道吧 。
差集:A,B是两个集合,所有属于A且不属于B的元素构成的集合, 就是差集。
交集:A,B是两个集合,既属于A又属于B的元素构成的集合, 就是交集。
并集:A,B是两个集合,把他们所有的元素合并在一起组成的集合,就是并集。
说完了定义,接下来说下Python怎么求两个列表中的差集、交集与并集的方法 。
求两个list差集:
list1 = [1,2,3] list2 = [3,4,5] temp = [] for i in list1: if i not in list2: temp.append(i) print(temp) #[1,2]
list1 = [1,2,3] list2 = [3,4,5] temp = list(set(list1) ^ set(list2)) print(temp)
list1 = [1,2,3] list2 = [3,4,5] temp = list(set(list1).difference(set(list2))) print(temp)
求两个list交集:
list1 = [1,2,3] list2 = [3,4,5] temp = list(set(list1).intersection(set(list2))) print(temp) #[3]
求两个list并集:
list1 = [1,2,3] list2 = [3,4,5] temp = list(set(list1).union(set(list2))) print(temp) #[1, 2, 3, 4, 5]
如果对于参考答案有不认同的,大家可以在评论区指出和补充,欢迎留言!


