pythonlist如何去重
要去除python列表中的重复元素,有很多方法
直观方法
先建立一个新的空列表,再遍历原来的列表,利用逻辑关系notin来去重。
numbers=[1,7,3,2,5,6,2,3,4,1,5]
new_numbers=[]
forxinnumbers:
ifxnotinnew_numbers:
new_numbers.append(x)
print(new_numbers)
此方法过程复杂,但是保证了列表的顺序性。
使用set()的自动去重功能
numbers=[1,7,3,2,5,6,2,3,4,1,5]
new_numbers=list(set(numbers))
print(new_numbers)
此方法将列表转化为集合再转化为列表,利用集合的自动去重功能。简单快速。缺点是:使用set方法无法保证去重后的顺序。
但是,可以通过列表中索引(index)的方法保证去重后的顺序不变。
numbers=[1,7,3,2,5,6,2,3,4,1,5]
new_numbers=list(set(numbers))
new_numbers.sort(key=numbers.index)
print(new_numbers)
以上内容为大家介绍了python培训之list如何去重,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python正则表达式中的零宽断言
python正则表达式中的零宽断言1、概念有些元字符不匹配任何字符,只是简单的表示成功或失败,所以这些字符也叫零宽断言。2、符号举例(1)|或操作...详情>>
2023-11-14 11:35:03
python方法的绑定和未绑定
python方法的绑定和未绑定1、说明未绑定对象的方法:无self参数的方法,通过定义类调用函数,返回未绑定self的方法。绑定对象的方法:带self参...详情>>
2023-11-14 09:53:02
python海象运算符的使用
python海象运算符的使用1、在判断条件下允许操作。在一定程度上简化了代码,但降低了可读性。i=len((l:=[1,2,3]))#先对l进行赋值,在对i赋值whi...详情>>
2023-11-14 02:38:21
pythonelif语句报错是什么原因
python的else和elif语句也可以叫做子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子...详情>>
2023-11-13 21:46:35热门推荐
技术干货






