您好,欢迎访问一九零五行业门户网

python列表如何去重

python列表去重的方法:1、利用字典的【fromkeys()】和【keys()】方法去重;2、集合的可迭代方法;3、用for循环,代码为【for x in l3:if x not in l4:l4.append(x)】。
python列表去重的方法:
第一种方法,利用字典的fromkeys()和keys()方法
#列表去重l = [1,2,3,4,5,6,6,5,4,3,2,1]#创建一个空字典d = {}#用字典的fromkeys()方法去重,得到一个字典,去重之后的元素为键,值为none的字典#{1: none, 2: none, 3: none, 4: none, 5: none, 6: none}#fromkeys(iterable,value=none)l = d.fromkeys(l)print(l) #{1: none, 2: none, 3: none, 4: none, 5: none, 6: none}#用字典的keys()方法得到一个类似列表的东西,但不是列表。keys()函数返回的是一个dict_keys对象:#以字典的键作为元素的一个类列表l = l.keys()#print(l) #dict_keys([1, 2, 3, 4, 5, 6])l = list(l)print(l) #[1, 2, 3, 4, 5, 6]#可以用列表的sort()方法排序,默认是升序# print(l.sort())l.sort(reverse=true) #升序print(l)#[6, 5, 4, 3, 2, 1]print('-----------------------------')
第二种方法,集合,集合是可迭代的
l2 = [1,2,3,4,5,6,6,5,4,3,2,1]l2=set(l2)print(l2) #{1, 2, 3, 4, 5, 6}l2 = list(l2)print(l2) #[1, 2, 3, 4, 5, 6]print('-------------------------------')
第三种方法,用for循环
l3 = [1,2,3,4,5,6,6,5,4,3,2,1]l4 = []for x in l3: if x not in l4: l4.append(x)print(l4) #[1, 2, 3, 4, 5, 6]
相关免费学习推荐:python视频教程
以上就是python列表如何去重的详细内容。
其它类似信息

推荐信息