文章目录
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)))