【Python】列表的去重

经常需要使用到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())

猜你喜欢

转载自blog.csdn.net/lvluobo/article/details/81003791
今日推荐