现在的位置: 主页 > 联系方式 > 文章列表

python中sort和sorted总结

作者:福建省医学会血液病学分会 来源:www.fjhematology.org 发布时间:2017-09-11 13:59:32
 

python中sort和sorted总结 概要 list.sort(cmp=None, key=None, reverse=False):

list的一个成员函数,调用时list本身发生改变

cmp: 排序函数 key: 排序关键字 reverse: 升序(False)或者降序(True) sorted(iterable, cmp=None, key=None, reverse=False):

python的一个内部函数,对可迭代类型数据进行排序并返回,但不影响数据本身

cmp: 排序函数 key: 排序关键字 reverse: 升序(False)或者降序(True) 简单排序 a1 = [3,2,1,6,5,4] a2 = [3,2,1,6,5,4] print a1 # [3, 2, 1, 6, 5, 4] a1.sort() #调用成员函数进行排序(默认为升序:reversr=False),返回值为‘none’ print a1 # 重新输出a1,此时的a1已经改变:[1, 2, 3, 4, 5, 6] a1.sort(reverse=True) # 降序 print a1 # [6, 5, 4, 3, 2, 1] print '\n' print a2 # [3, 2, 1, 6, 5, 4] print sorted(a2) # 对a2进行排序:[1, 2, 3, 4, 5, 6] print sorted(a2,reverse=True) #降序:[6, 5, 4, 3, 2, 1] print a2 # 此时a2不变:[3, 2, 1, 6, 5, 4] [3, 2, 1, 6, 5, 4] [1, 2, 3, 4, 5, 6] [6, 5, 4, 3, 2, 1] [3, 2, 1, 6, 5, 4] [1, 2, 3, 4, 5, 6] [6, 5, 4, 3, 2, 1] [3, 2, 1, 6, 5, 4] 根据cmp函数进行排序 a1 = [['a',3],['c',2],['b',4],['d',1]] a2 = [['a',3],['c',2],['b',4],['d',1]] print a1 a1.sort() # 默认根据每一个子列表中起始元素(索引为0)进行排序 print a1 a1.sort(cmp = lambda x,y:cmp(x[0],y[0])) # 根据每一个子列表中起始元素(索引为0)进行排序 print a1 a1.sort(cmp = lambda x,y:cmp(x[1],y[1])) # 根据每一个子列表中索引为1的元素进行排序 print a1 print '\n' ## 用sorted函数对a2排序,不改变a2自身的值,其他与a2.sort()相同 print a2 print sorted(a2) print a2,'\n' print sorted(a2,cmp = lambda x,y:cmp(x[0],y[0])) print a2,'\n' print sorted(a2,cmp = lambda x,y:cmp(x[1],y[1])) print a2 [['a', 3], ['c', 2], ['b', 4], ['d', 1]] [['a', 3], ['b', 4], ['c', 2], ['d', 1]] [['a', 3], ['b', 4], ['c', 2], ['d', 1]] [['d', 1], ['c', 2], ['a', 3], ['b', 4]] [['a', 3], ['c', 2], ['b', 4], ['d', 1]] [['a', 3], ['b', 4], ['c', 2], ['d', 1]] [['a', 3], ['c', 2], ['b', 4], ['d', 1]] [['a', 3], ['b', 4], ['c', 2], ['d', 1]] [['a', 3], ['c', 2], ['b', 4], ['d', 1]] [['d', 1], ['c', 2], ['a', 3], ['b', 4]] [['a', 3], ['c', 2], ['b', 4], ['d', 1]] 根据key关键字进行排序 a1 = [['a',3],['c',2],['b',4],['d',1]] a2 = [['a',3],['c',2],['b',4],['d',1]] print a1 a1.sort() # 默认根据每一个子列表中起始元素(索引为0)进行排序 print a1 a1.sort(key = lambda x:x[0]) # 根据每一个子列表中起始元素(索引为0)进行排序 print a1 a1.sort(key = lambda x:x[1]) # 根据每一个子列表中索引为1的元素进行排序 print a1 print '\n' ## 用sorted函数对a2排序,不改变a2自身的值,其他与a2.sort()相同 print a2 print sorted(a2) print a2,'\n' print sorted(a2,key = lambda x:x[0]) print a2,'\n' print sorted(a2,key = lambda x:x[1]) print a2 [['a', 3], ['c', 2], ['b', 4], ['d', 1]] [['a', 3], ['b', 4], ['c', 2], ['d', 1]] [['a', 3], ['b', 4], ['c', 2], ['d', 1]] [['d', 1], ['c', 2], ['a', 3], ['b', 4]] [['a', 3], ['c', 2], ['b', 4], ['d', 1]] [['a', 3], ['b', 4], ['c', 2], ['d', 1]] [['a', 3], ['c', 2], ['b', 4], ['d', 1]] [['a', 3], ['b', 4], ['c', 2], ['d', 1]] [['a', 3], ['c', 2], ['b', 4], ['d', 1]] [['d', 1], ['c', 2], ['a', 3], ['b', 4]] [['a', 3], ['c', 2], ['b', 4], ['d', 1]]

企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:鄂州SEO http://ezhou.4567w.com

  • 上一篇:编程原则:表驱动法
  • 下一篇:最后一页
  •