首页 > 代码库 > python的sorted相关

python的sorted相关

Python 字典排序

在python里,字典是内置的数据类型,是个无序的存储结构,每一个元素是key-value对:

>>> d{9: xinzhou, 3: chen, 5: wuhan, 1: yadan}>>> ss=sorted(d.items(),key=lambda d:d[0])            #主要看这里>>> ss[(1, yadan), (3, chen), (5, wuhan), (9, xinzhou)]>>> d{9: xinzhou, 3: chen, 5: wuhan, 1: yadan}>>> sss=sorted(d.items(),key=lambda d:d[1])>>> sss[(3, chen), (5, wuhan), (9, xinzhou), (1, yadan)]>>> sss=sorted(d.items(),key=lambda d:d[1],reverse=True)    #主要看这里>>> sss[(1, yadan), (9, xinzhou), (5, wuhan), (3, chen)]>>> sss=sorted(d.items(),key=lambda d:d[1],reverse=False)>>> sss[(3, chen), (5, wuhan), (9, xinzhou), (1, yadan)]

 

dict1={A: 9, C: 5, B: 1, E: 14, D: 3, G: 3, F: 3, I: 9, H: 7, J: 1, L: 2, O: 8, N: 3, P: 4, S: 10, R: 5, U: 1, T: 17, W: 1, V: 1}#对字典按值排序,以元组的形式返回print sorted(dict1.iteritems(),key=lambda dict1:dict1[1],reverse=True)#对字典按键排序,以元组的形式返回print sorted(dict1.iteritems(),key=lambda dict1:dict1[0],reverse=False)

 

参考下其他类型的排序:(估计python2)

>>> student_tuples = [        (john, A, 15),        (jane, B, 12),        (dave, B, 10),]>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age[(dave, B, 10), (jane, B, 12), (john, A, 15)]

 

例如:

>>> a=[(5,"chen"),(3,"hang"),(7,"wang"),(4,"yadan")]>>> a[(5, chen), (3, hang), (7, wang), (4, yadan)]>>> aa=sorted(a,key=lambda a:a[0],reverse=False)>>> aa[(3, hang), (4, yadan), (5, chen), (7, wang)]>>> aaa=sorted(a,key=lambda a:a[1],reverse=False)>>> aaa[(5, chen), (3, hang), (7, wang), (4, yadan)]

 

 

 

 

dd

Python 字典排序

在python里,字典是内置的数据类型,是个无序的存储结构,每一个元素是key-value对:

dict1={‘A‘: 9, ‘C‘: 5, ‘B‘: 1, ‘E‘: 14, ‘D‘: 3, ‘G‘: 3, ‘F‘: 3, ‘I‘: 9, ‘H‘: 7, ‘J‘: 1, ‘L‘: 2, ‘O‘: 8, ‘N‘: 3, ‘P‘: 4, ‘S‘: 10, ‘R‘: 5, ‘U‘: 1, ‘T‘: 17, ‘W‘: 1, ‘V‘: 1}
#对字典按值排序,以元组的形式返回
print sorted(dict1.iteritems(),key=lambda dict1:dict1[1],reverse=True)
#对字典按键排序,以元组的形式返回
print sorted(dict1.iteritems(),key=lambda dict1:dict1[0],reverse=False)

python的sorted相关