Python sorted

来源:互联网 发布:windows模拟器 编辑:程序博客网 时间:2024/05/20 09:08
sorted(iterable, cmp=None, key=None, reverse=False)

Key Functions

Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.


Operator Module Functions

The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter, attrgetter, and starting in Python 2.6 a methodcaller function.


from operator import attrgetter, itemgetter, methodcallerimport operator# from skiplistcollections import SkipListDictstudent_tuples = [        ('john', 'A', 15),        ('jane', 'B', 12),        ('dave', 'B', 10),        ("t-bed", 'C', 9)]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))    def weighted_grade(self):        return 'CBA'.index(self.grade) / float(self.age)student_objects = [        Student('john', 'A', 15),        Student('jane', 'B', 12),        Student('dave', 'B', 10),        Student("t-bed", 'C', 9)]# https://wiki.python.org/moin/HowTo/Sorting# https://docs.python.org/3/library/operator.html#module-operatorif __name__ == '__main__':    print sorted(student_tuples, key=itemgetter(0))    print sorted(student_objects, key=attrgetter('age'))    print sorted(student_tuples, key=lambda student: student[2])    # The operator module functions allow multiple levels of sorting.    print sorted(student_objects, key=attrgetter('grade', 'age'))    print sorted(student_objects, key=methodcaller('weighted_grade'))    # print sorted(student_objects, key=itemgetter(0))  #AttributeError: Student instance has no attribute '__getitem__'    print "============================================================================"    x = "hello"    y = operator.iadd(x, " world")    print x    print y    s = ['h', 'e', 'l', 'l', 'o']    t = operator.iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])    print s    print t

The result is:

[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15), ('t-bed', 'C', 9)][('t-bed', 'C', 9), ('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)][('t-bed', 'C', 9), ('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)][('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12), ('t-bed', 'C', 9)][('t-bed', 'C', 9), ('jane', 'B', 12), ('dave', 'B', 10), ('john', 'A', 15)]============================================================================hellohello world['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']


Inplace Operators

Many operations have an “in-place” version. Listed below are functionsproviding a more primitive access to in-place operators than the usual syntaxdoes; for example, thestatementx+=y is equivalent tox=operator.iadd(x,y). Another way to put it is to say thatz=operator.iadd(x,y) is equivalent to the compound statementz=x;z+=y.

In those examples, note that when an in-place method is called, the computationand assignment are performed in two separate steps. The in-place functionslisted below only do the first step, calling the in-place method. The secondstep, assignment, is not handled.

For immutable targets such as strings, numbers, and tuples, the updatedvalue is computed, but not assigned back to the input variable:

>>>
>>> a = 'hello'>>> iadd(a, ' world')'hello world'>>> a'hello'

For mutable targets such as lists and dictionaries, the inplace methodwill perform the update, so no subsequent assignment is necessary:

>>>
>>> s = ['h', 'e', 'l', 'l', 'o']>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']>>> s['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> [name for name in dir(operator) if not name.startswith('_')]['abs', 'add', 'and_', 'attrgetter', 'concat', 'contains', 'countOf', 'delitem', 'delslice', 'div', 'eq', 'floordiv', 'ge', 'getitem', 'getslice', 'gt', 'iadd', 'iand', 'iconcat', 'idiv', 'ifloordiv', 'ilshift', 'imod', 'imul', 'index', 'indexOf', 'inv', 'invert', 'ior', 'ipow', 'irepeat', 'irshift','isCallable', 'isMappingType', 'isNumberType', 'isSequenceType', 'is_', 'is_not', 'isub', 'itemgetter', 'itruediv', 'ixor', 'le', 'lshift', 'lt', 'methodcaller', 'mod', 'mul', 'ne', 'neg', 'not_', 'or_', 'pos', 'pow', 'repeat', 'rshift', 'sequenceIncludes', 'setitem', 'setslice', 'sub', 'truediv', 'truth', 'xor']'''Most of the names listed are self-evident. The group of names prefixed with i and the name of another operator -- e.g., iadd, iand, etc. -- correspond to the augmented assignment operators -- e.g., +=, &=, etc. These change their first argument in place, if it is mutable; if not, the function works like the one without the i prefix: it simply returns the result of the operation.'''


References:

https://wiki.python.org/moin/HowTo/Sorting

https://docs.python.org/3/library/operator.html#module-operator

https://pypi.python.org/pypi/skiplistcollections

http://blog.csdn.net/u011489043/article/details/70197020