1. cmp(比较大小的函数)
eg:
str1='abc'
str2='lmn'
print cmp(str1,str2)
>>>-1
str1<str2 -1
str1>str2 1
str1==str2 0
注意:cmp(“abc”,“abcd”)结果是-1,更长的序列要“大”
在Python2中经常使用这一个函数,但是在Python3中取消了这一个函数,在operator中增加了新的几个函数。
operator.lt(a, b)
operator.le(a, b)
operator.eq(a, b)
operator.ne(a, b)
operator.ge(a, b)
operator.gt(a, b)
operator.__lt__(a, b)
operator.__le__(a, b)
operator.__eq__(a, b)
operator.__ne__(a, b)
operator.__ge__(a, b)
operator.__gt__(a, b)
其作用相当于
lt(a, b) 相当于 a < b (less than)
le(a,b) 相当于 a <= b (less equal)
eq(a,b) 相当于 a == b (equal)
ne(a,b) 相当于 a != b (negative equal)
gt(a,b) 相当于 a > b (greater than)
ge(a, b)相当于 a>= b (greater equal)
有点类似于shell指令。
2.sorted
sorted('123456') 字符串
['1', '2', '3', '4', '5', '6']
sorted([1,4,5,2,3,6]) 列表
[1, 2, 3, 4, 5, 6]
sorted({1:'q',3:'c',2:'g'}) 字典, 默认对字典的键进行排序
[1, 2, 3]
sorted({1:'q',3:'c',2:'g'}.keys()) 对字典的键
[1, 2, 3]
sorted({1:'q',3:'c',2:'g'}.values()) 对字典的值
['c', 'g', 'q']
sorted({1:'q',3:'c',2:'g'}.items()) 对键值对组成的元组的列表
[(1, 'q'), (2, 'g'), (3, 'c')]
2, 对元素指定的某一部分进行排序,关键字排序
s = ['Chr1-10.txt','Chr1-1.txt','Chr1-2.txt','Chr1-14.txt','Chr1-3.txt','Chr1-20.txt','Chr1-5.txt']
我想要按照-后的数字的大小升序排序。要用到key
sorted(s, key=lambda d : int(d.split('-')[-1].split('.')[0]))
['Chr1-1.txt', 'Chr1-2.txt', 'Chr1-3.txt', 'Chr1-5.txt', 'Chr1-10.txt', 'Chr1-14.txt', 'Chr1-20.txt']
3.你可以定制你想要的key, 如 key = lambda x : len(x) 按照序列的长度去排序。
key= lambda x : (x[1], x[0]) 按二个元素,再第一个 等等。
注意:list.sort()方法仅被定义在list中,相反地sorted()方法对所有的可迭代序列都有效。
sort()作用于变量本身,而sorted()并不改变变量本身。
再看一个例子:
>>> class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
>>> student_objects = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),
]
>>> sorted(student_objects, key=lambda student: student.age) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
拼接最小序字典练习题:
class Prior:
def findSmallest(self, strs, n):
# write code here
s=sorted(strs,cmp=lambda x,y: cmp(x+y,y+x))
return ''.join(s)
4.reverse使用
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
默认是升序,如果使用reverse=True
代表降序
引用:
http://blog.csdn.net/sushengmiyan/article/details/11332589
http://www.jb51.net/article/57678.htm
http://www.cnblogs.com/kellyseeme/p/5525052.html