python(sorted()函数)
2018-01-31 21:02
204 查看
一、什么是sorted()?
#sorted()函数 可以对数字(从小到大。从大到小)或字符串(ASCII编码)进行排序
#对数字进行排序二、如何使用?
list1 = [1,52,2,44,1132,54,9]
#默认按升序排序
rs = sorted(list1)
print(rs)
执行结果:[1, 2, 9, 44, 52, 54, 1132]
#实现一个按照降序排序的函数
#如果x>y 返回-1,如果x<y,返回1,是按降序排序
#如果x>y,返回1,如果x<y,返回-1 是按升序排序
def reversed(x,y):
if x>y:
return -1
if x<y:
return 1
return 0
rs = sorted(list1,reverse=True)
print(rs)
执行结果:[1132, 54, 52, 44, 9, 2, 1]
list2 =['s','t','e','a','g']
rs = sorted(list2,reversed)
print(rs)
执行结果: ['t', 's', 'g', 'e', 'a']
#如果需要按照实现字符串的排序,忽略大小写,只按照小写的a-z进行排序
list3 = ['if','with','BOY','Adc','fDk']
def char_sort(string1,string2):
#把两个字符串全部转换为小写或者大写
s1 = string1.lower()
s2 = string2.lower()
if s1>s2:
return -1
if s1<s2:
return 1
return 0
rs = sorted(list3,char_sort)
print(rs)
执行结果:['with', 'if', 'fDk', 'BOY', 'Adc']
#sorted()函数 可以对数字(从小到大。从大到小)或字符串(ASCII编码)进行排序
#对数字进行排序二、如何使用?
list1 = [1,52,2,44,1132,54,9]
#默认按升序排序
rs = sorted(list1)
print(rs)
执行结果:[1, 2, 9, 44, 52, 54, 1132]
#实现一个按照降序排序的函数
#如果x>y 返回-1,如果x<y,返回1,是按降序排序
#如果x>y,返回1,如果x<y,返回-1 是按升序排序
def reversed(x,y):
if x>y:
return -1
if x<y:
return 1
return 0
rs = sorted(list1,reverse=True)
print(rs)
执行结果:[1132, 54, 52, 44, 9, 2, 1]
list2 =['s','t','e','a','g']
rs = sorted(list2,reversed)
print(rs)
执行结果: ['t', 's', 'g', 'e', 'a']
#如果需要按照实现字符串的排序,忽略大小写,只按照小写的a-z进行排序
list3 = ['if','with','BOY','Adc','fDk']
def char_sort(string1,string2):
#把两个字符串全部转换为小写或者大写
s1 = string1.lower()
s2 = string2.lower()
if s1>s2:
return -1
if s1<s2:
return 1
return 0
rs = sorted(list3,char_sort)
print(rs)
执行结果:['with', 'if', 'fDk', 'BOY', 'Adc']
相关文章推荐
- python中List的sort方法(或者sorted内建函数)的用法
- python3----函数(sort和sorted)
- python sort() sorted() 与argsort()函数的区别
- python sorted()函数解析
- python笔记(2)排序函数sorted的用法
- python中List的sort方法(或者sorted内建函数)的用法
- python中List的sort方法(或者sorted内建函数)的用法
- python基础——sorted()函数
- Python 几个内建函数: map, reduce,filter,sorted 整理
- python sorted函数
- Python3中sorted函数没有cmp关键字
- [Python]sorted()函数与list.sort()函数
- python - flask对sorted()函数的使用
- python sorted()函数用法
- Python中的排序函数argsort,sort,sorted用法
- 【转】python的内建函数:filter,map,reduce,lambda,sorted等
- python—sort()与sorted()函数
- python中sort() sorted() 和argsort()函数
- Python笔记- 匿名函数lambda(),过滤函数filter(),求素数,排序sorted
- python中排序,函数sort、sorted、argsort,collections.OrderedDict类