【Python】列表的去重,两个列表list并集,差集,

list去重

经常需要使用到list去重,面试的时候也常问及到这点.
测试环境Python3.6.0+Pycharm

for循环

a_list =[1,1,2,3,3,4,5,3,4]
b_list = []
for i in a_list:
    if i not in b_list:
        b_list.append(i)
print(b_list)   # [1, 2, 3, 4, 5]

list(set())

a_list =[1,1,2,3,3,4,5,3,4]
a_set=set(a_list)   
print(a_set)        # {1, 2, 3, 4, 5}
print(type(a_set))  # <class 'set'>
b_list = list(a_set)
print(b_list)       # [1, 2, 3, 4, 5] 
print(type(b_list)) # <class 'list'>

因为使用set后,type变成了set,所以需要使用list,转换下类型.使用set会改变原顺序

其实一句就可以解决

b_list = list(set(a_list))
print(b_list)   # [1, 2, 3, 4, 5]

因为简洁,所以喜欢使用list(set())

两个list的差集/并集/交集

差集

a 和b的差集
方式有几种

最简单的for循环

a = [1,2,3]
b = [1,3]

c = []
for i in a:
    if i not in b:
        c.append(i)

高级一些的列表生成式

c = [i for i in a if i not in b]

再简化点的,直接使用set里的difference进行操作

c = list(set(a).difference(set(b)))

并集(两个list的去重)

list相加再去重

c = a+b
c = list(set(c))

直接使用set().union函数

c = list(set(a).union(set(b)))

交集

使用intersection函数

c = list(set(a).intersection(set(b)))  
  • 6
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值