Python内置工具(tools)总结
Python提供了以下几个内置tools模块,简化开发operator collections itertools functools除此之外,还有一些其他工具,比如mimetools、unittest等,上述四个tools作用于内建类型和函数、类等,比较通用,也较为常用。-operator : 内置的操作符模块-collections : 简化容器类型的一些操作和使用-itertool
Python提供了以下几个内置tools模块,简化开发
operator collections itertools functools
除此之外,还有一些其他工具,比如mimetools、unittest等,上述四个tools作用于内建类型和函数、类等,比较通用,也较为常用。 
  -operator : 内置的操作符模块 
  -collections : 简化容器类型的一些操作和使用 
  -itertools : 可迭代类型工具 
  -functools : 函数工具,尤其是装饰器
operator
operator提供了一个函数与符号的相互转换,方便我们在编程时选择: 
  examples 
(1)符号转函数: 
  比如在一些需要某些符号功能,却需要提供该符号的函数表示时,尤其是在map reduce filter等的key 和cmp里面
from operator import add
print reduce(add,range(10))(2)函数转符号: 
  这个例子有点特别,但是在类定义中常见,add->__add__这种方式差别跟python的变量有关。 
  附:python变量命名方式(来自网络): 
python变量命名规范 
  下面是python符号函数映射表
class A():
    def __init__(self,num):
        self.num=num
    def __add__(self,other):
        return self.num+other.num| Operation | Syntax | Function | 
|---|---|---|
| Addition | a + b | add(a, b) | 
| Concatenation | seq1 + seq2 | concat(seq1, seq2) | 
| Containment | Test obj in seq | contains(seq, obj) | 
| Division | a / b | div(a, b) (without future.division) | 
| Division | a / b | truediv(a, b) (with future.division) | 
| Division | a // b | floordiv(a, b) | 
| Bitwise And | a & b | and_(a, b) | 
| Bitwise Exclusive Or | a ^ b | xor(a, b) | 
| Bitwise Inversion | ~ a | invert(a) | 
| Bitwise Or | a | b | or_(a, b) | 
| Exponentiation | a ** b | pow(a, b) | 
| Identity | a is b | is_(a, b) | 
| Identity | a is not b | is_not(a, b) | 
| Indexed Assignment | obj[k] = v | setitem(obj, k, v) | 
| Indexed Deletion | del obj[k] | delitem(obj, k) | 
| Indexing | obj[k] | getitem(obj, k) | 
| Left Shift | a << b | lshift(a, b) | 
| Modulo | a % b | mod(a, b) | 
| Multiplication | a * b | mul(a, b) | 
| Negation (Arithmetic) | - a | neg(a) | 
| Negation (Logical) | not a | not_(a) | 
| Positive | + a | pos(a) | 
| Right Shift | a >> b | rshift(a, b) | 
| Sequence Repetition | seq * i | repeat(seq, i) | 
| Slice Assignment | seq[i:j] = values | setitem(seq, slice(i, j), values) | 
| Slice Deletion | del seq[i:j] | delitem(seq, slice(i, j)) | 
| Slicing | seq[i:j] | getitem(seq, slice(i, j)) | 
| String Formatting | s % obj | mod(s, obj) | 
| Subtraction | a - b | sub(a, b) | 
| Truth Test | obj | truth(obj) | 
| Ordering | a < b | lt(a, b) | 
| Ordering | a <= b | le(a, b) | 
| Equality | a == b | eq(a, b) | 
| Difference | a != b | ne(a, b) | 
| Ordering | a >= b | ge(a, b) | 
| Ordering | a > b | gt(a, b) | 
关于细节内容可以参考 
python library - operator
collections
主要是为容器类型: list, set, and tuple提供了一些便利 
  有以下几个类型
| type | describe | 
|---|---|
| namedtuple | factory function for creating tuple subclasses with named fields | 
| deque | list-like container with fast appends and pops on either end | 
| Counter | dict subclass for counting hashable objects | 
| OrderedDict | dict subclass that remembers the order entries were added | 
| defaultdict | dict subclass that calls a factory function to supply missing values | 
namedtuple 
  主要用于对tuple里面的分量进行命名,生成一个tuple的子类,这个子类继承了原来的tuple类,有相同的属性方法。
from collections import namedtuple
mytuple=namedtuple('mytuple',('name','age')])
first=mytuple('tom',19)
print first.name,first.age这种namedtuple可以用来对获取的的数据库数据进行命名,我们从数据库获取的每条记录都是用一个tuple,不方便我们取属性,如果换成我们自定义的namedtuple类型,更便于操作和理解。 
deque 
  这是一种队列类型,有队列类型的相关操作,可以弥补list这种广义表类型的某些不足,比如在前面插入较慢(这里你可以查找一些python的资料,对于python的list前段吧插入时会整个后移list,效率较低) 
  关于这种类型相应的方法支持可以参考后面附上的python library链接 
Counter 
  可以理解为一个计数字典
from collections import *
d = Counter("hello world hello BJ".split())
print d
# OUT : Counter({'hello': 2, 'world': 1, 'BJ': 1})
print d['SH']
# OUT : 0返回一个字典的子类,键值为可迭代对象里的对象和相应数量。 
  对于这个字典里没有的键,返回0,类似于普通字典的 d.get(‘SH’,0) 
  关于这种类型的其他方法也可参考官方文档,讲得很清楚。 
OrderedDict 
  有序字典,字典中的键按序排放,加入了一些与顺序有关的操作,比如popitem()等 
defaultdict 
  对于一个defaultdict类型,当你去访问它的键值时,如果没有这个键,它会调用一个可调用对象,将返回值赋给这个键。
call1 = int
call2 = list
call3 = lambda :4
from colletions import defaultdict
mydict1 = defaultdict(call1)
mydict2 = defaultdict(call2)
mydict3 = defaultdict(call3) 
print mydict1['not'],mydict2['not'],mydict3['not']
# OUT : 0 [] 4
# 执行过程是,去取这个键的值,如果没有,调用call1(None),...
# 如果你想知道我说的对不对,可以把call3 = lambda x:4 ,试试,看他的报错就知道了。colletions后面还列出了一些类,用于继承和isinstance判断 
  本节参考: 
python library - collections
itertools
可以参考: 
python library - itertools 
  前面的都比较好理解 
  主要想解释下tee,感觉tee像是对原迭代对象的n份deepcopy,不知道他说的那个split是不是这个意思 
Combinatoric generators部分: 
  对于s=’ABCD’
| Iterator | Arguments | Results | 
|---|---|---|
| product() | p, q, … [repeat=1] | cartesian product, equivalent to a nested for-loop | 
| permutations() | p[, r] | r-length tuples, all possible orderings, no repeated elements | 
| combinations() | p, r | r-length tuples, in sorted order, no repeated elements | 
| combinations_with_replacement() | p, r | r-length tuples, in sorted order, with repeated elements | 
| product(‘ABCD’, repeat=2) | 类似 Ann <script type="math/tex" id="MathJax-Element-1">A_n^n</script> | AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD | 
| permutations(‘ABCD’, 2) | 类似 A2n <script type="math/tex" id="MathJax-Element-2">A_n^2</script> | AB AC AD BA BC BD CA CB CD DA DB DC | 
| combinations(‘ABCD’, 2) | 类似 C2n <script type="math/tex" id="MathJax-Element-3">C_n^2</script> | AB AC AD BC BD CD | 
| combinations_with_replacement(‘ABCD’, 2) | C2n <script type="math/tex" id="MathJax-Element-4">C_n^2</script>+AA…DD | AA AB AC AD BB BC BD CC CD DD | 
functools
这里面前面几个工具是用来衔接的old-new,这点感觉跟那个__future__模块很像 
  后面的跟函数闭包里面的装饰器有关,一共有三个函数(类) 
  update_wrapper wraps partial 
  wraps是简化了的update_wrapper 
  关于这三个: 
  update_wrapper:Update a wrapper function to look like the wrapped function. 
  wraps:This is a convenience function for invoking update_wrapper() as a function decorator when defining a wrapper function. 
  partial是一个类,有多个属性。 
  前面俩个可以参考官方例子,partial可以用于固定函数参数
from functools import partial
def basefunc(a,b):
    return a+b
newfunc = partial(basefunc,b=1)
print newfunc(5)
# OUT : 6
#这里要考虑函数默认参数的问题,如果newfunc = partial(basefunc,a=1),print 时会报错,必须print newfunc(b=5),关于函数默认参数赋值问题,基本上原则是默认赋值的放后面,否则要在调用函数时使用形参更多推荐
 
 




所有评论(0)