python中对两个 list 求交集,并集和差集
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]) >>> union >>> b [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> difference=[v for v in a if v not in b] >>> difference [] >>> a=[1,2,3,4,5,6,7,8,9,10] >>> b=[1,2,3,4,5] >>> difference=[v for v in a if v not in b] >>> difference [6, 7, 8, 9, 10]
2、效率较高的、并且可以去除重复数据的做法:
>>> a=[1,2,3,4,5,6,7,8,9,10] >>> b=[1,2,3,4,5] >>> intersection=list(set(a).intersection(set(b))) >>> intersection [1, 2, 3, 4, 5] >>> union=list(set(a).union(set(b))) >>> union [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> difference = list(set(a).difference(set(b))) >>> difference [8, 9, 10, 6, 7]
【Reference】
posted on 2018-04-17 16:47 CuriousZero 阅读(442) 评论(0) 编辑 收藏 举报