python-列表去重,字典排序

1 Python对列表去重的4种方法

1.1 使用set的特征,python 的set 和其他语言类似,是一个无序不重复的元素集

orgList = [1,0,3,7,7,5]

#list()方法是把字符串str或元组转成数组

formatList = list(set(orgList))

print (formatList)

1.2 使用keys() 方法

orgList=[1,0,3,7,7,5]

formatList=list({}.fromkeys(orgList).keys())

print(formatList)

以上的结果是没有保存原来的顺序

1.3 循环遍历法

orgList=[1,0,3,7,7,5]

formatList=[]

for id in orgList:

     if  id not in formatList:

           formatList.append(id)

print(formatList)

1.4 按照索引再次排序

orgList=[1,0,3,7,7,5]

formatList=list(set(orgList))

formatList.sort(key=orgList.index)

print(formatList)

2 对字典进行排序

按照values 的值排序输出,或者别的奇怪的顺序输出。我们只需要把字典转化为list 或者tuple。把字典的每一对键值转化为list 中的两位子list 或者子tuple再输出,

eg:

x={2:1,3:4,4:2,1:5,5:3}

import operator

sorted_x=sorted(x.items(),key=operator.itemgetter(0))# 按照item中的第一个字符进行排序,即按照key 排序

python-列表去重,字典排序_第1张图片

 

你可能感兴趣的:(python)