直接上代码,有三种方法,第三种调用库函数效率最高 # ! /usr/bin/env python # encoding:utf-8 if __name__ == '__main__': a = [1,2,3,4,5] b = [2,3,6,7] u =[] dif =[] intersec = [] '''方法一,最简单的方法,容易想到的''' for item in a: u.append(item) if item in b: intersec.append(item) if item no
python中对两个 list 求交集,并集和差集: 1.首先是较为浅白的做法: >>> a=[1,2,3,4,5,6,7,8,9,10] >>> b=[1,2,3,4,5] >>> intersection=[v for v in a if v in b] >>> intersection [1, 2, 3, 4, 5] >>> union=b.extend([v for v in a]) >>>