liting李

2021-04-23   阅读量: 29

Python

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]


92.3077 1 0 关注作者 收藏

评论(0)


暂无数据

推荐课程