python中如何去除列表中重复元素?

方法一:

         用内置函数set:

    

1 list1 = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9]
2 list2 = list(set(list1))
3 print(list2)

 

方法二:

      遍历去除重复

1 list1 = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9]
2 list2=[]
3 for i in list1:
4     if not i in list2:
5         list2.append(i)
6 print(list2)

 列表推导式

1 list1 = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9]
2 list2=[]
3 [list2.append(i) for i in list1 if not i in list2]

 

posted @ 2017-12-22 22:50  老A队长  阅读(53956)  评论(0编辑  收藏  举报