python怎么对列表中元素去重复-Python教程

资源魔 52 0

正在Python中对列表中元素去反复有如下几种办法:

办法一:

用内置函数set:(保举:python中set是甚么意义)

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

办法二:

遍历去除了反复(保举:正在Python中遍历列表的办法有哪些)

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

列表推导式

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

更多Python相干技巧文章,请拜访Python教程栏目进行学习!

以上就是python怎样对列表中元素去反复的具体内容,更多请存眷资源魔其它相干文章!

标签: python教程 python编程 python使用问题 Python列表元素去重复

抱歉,评论功能暂时关闭!