Python sorted

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, methodcaller
import operator
# from skiplistcollections import SkipListDict

student_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-operator
if __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)]
============================================================================
hello
hello 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


1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、下载 4使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、 4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值