python去重的几种方法

 

from collections import OrderedDict
list1 = [1,5,2,1,10]
print(list(set(list1))) #[1, 2, 10, 5] 这种方式会改变list里面元素的位置


"""
先介绍fromkeys()函数
fromkeys()就是根据序列生成字典
"""
new1 = OrderedDict.fromkeys(["name","age","school"])
print(new1) #OrderedDict([('name', None), ('age', None), ('school', None)])  , 没有提供value,所以默认是none

new2 = OrderedDict.fromkeys(["name","age","school"],['shun','18',"shu"])
print(new2)#OrderedDict([('name', ['shun', '18', 'shu']), ('age', ['shun', '18', 'shu']), ('school', ['shun', '18', 'shu'])])

new = OrderedDict.fromkeys(list1)
print(new)  #OrderedDict([(1, None), (5, None), (2, None), (10, None)])
print(list(new.keys())) #[1, 5, 2, 10]

import numpy as np
nd = np.array(list1)
print(nd) #[ 1  5  2  1 10]
print(np.unique(nd)) #[ 1  2  5 10]  元素位置发生了变化

 

posted @ 2023-02-05 20:55  朵朵奇fa  阅读(136)  评论(0编辑  收藏  举报