python内置方法、模块讲解(二十七)

  • 2016-07-03 17:16:08
  • 1161
  • 0

 

七十、sorted方法

1、定义:

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

2、解释:生成一个整理好的list。其中iterable为可迭代对象,cmp为用来排序的比较函数, key为用来排序的关键值,reversed为是否倒序。

3、举例:

from operator import itemgetter
a = [{"name":"aa", "num":2}, {"name":"bb", "num":1},
     {"name":"cc", "num":0}, {"name": "ab", "num": 3}]
print sorted(a, key=lambda item:item["num"])
print sorted(a, cmp=lambda x, y:x['num']-y['num'])
print sorted(a, key=itemgetter("num"))
结果:
[{'num': 0, 'name': 'cc'}, {'num': 1, 'name': 'bb'}, {'num': 2, 'name': 'aa'}, {'num': 3, 'name': 'ab'}]
[{'num': 0, 'name': 'cc'}, {'num': 1, 'name': 'bb'}, {'num': 2, 'name': 'aa'}, {'num': 3, 'name': 'ab'}]
[{'num': 0, 'name': 'cc'}, {'num': 1, 'name': 'bb'}, {'num': 2, 'name': 'aa'}, {'num': 3, 'name': 'ab'}]
很明显以上三种方式可以实现列表中的字典按num关键字对应的value值进行排序,但使用cmp的效率要比其他两种低些。另外,当列表中是元组时,同理也有以上三种进行排序 

七十一、staticmethod类

1、定义:

 |  A static method does not receive an implicit first argument.
To declare a static method, use this idiom:
 |
 |       class C:
 |       def f(arg1, arg2, ...): ...
 |       f = staticmethod(f)
 |
 |  It can be called either on the class (e.g. C.f()) or on an instance
 |  (e.g. C().f()).  The instance is ignored except for its class.

2、解释:将一个函数转变成一个静态方法。ps:静态方法区别于classmethod主要在于调用:静态方法既可以被类和对象调用,而classmethod只能被类调用

3、举例:

从1中的定义中可以看到具体定义方式和调用方式(略)


发表评论

* *