首页 > 代码库 > 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相关
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。