您的位置:首页 > 编程语言 > Python开发

Python内置工具(tools)总结

2016-07-20 17:31 525 查看

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


OperationSyntaxFunction
Additiona + badd(a, b)
Concatenationseq1 + seq2concat(seq1, seq2)
ContainmentTest obj in seqcontains(seq, obj)
Divisiona / bdiv(a, b) (without future.division)
Divisiona / btruediv(a, b) (with future.division)
Divisiona // bfloordiv(a, b)
Bitwise Anda & band_(a, b)
Bitwise Exclusive Ora ^ bxor(a, b)
Bitwise Inversion~ ainvert(a)
Bitwise Ora | bor_(a, b)
Exponentiationa ** bpow(a, b)
Identitya is bis_(a, b)
Identitya is not bis_not(a, b)
Indexed Assignmentobj[k] = vsetitem(obj, k, v)
Indexed Deletiondel obj[k]delitem(obj, k)
Indexingobj[k]getitem(obj, k)
Left Shifta << blshift(a, b)
Moduloa % bmod(a, b)
Multiplicationa * bmul(a, b)
Negation (Arithmetic)- aneg(a)
Negation (Logical)not anot_(a)
Positive+ apos(a)
Right Shifta >> brshift(a, b)
Sequence Repetitionseq * irepeat(seq, i)
Slice Assignmentseq[i:j] = valuessetitem(seq, slice(i, j), values)
Slice Deletiondel seq[i:j]delitem(seq, slice(i, j))
Slicingseq[i:j]getitem(seq, slice(i, j))
String Formattings % objmod(s, obj)
Subtractiona - bsub(a, b)
Truth Testobjtruth(obj)
Orderinga < blt(a, b)
Orderinga <= ble(a, b)
Equalitya == beq(a, b)
Differencea != bne(a, b)
Orderinga >= bge(a, b)
Orderinga > bgt(a, b)
关于细节内容可以参考

python library - operator

collections

主要是为容器类型: list, set, and tuple提供了一些便利

有以下几个类型

typedescribe
namedtuplefactory function for creating tuple subclasses with named fields
dequelist-like container with fast appends and pops on either end
Counterdict subclass for counting hashable objects
OrderedDictdict subclass that remembers the order entries were added
defaultdictdict 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’

IteratorArgumentsResults
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, rr-length tuples, in sorted order, no repeated elements
combinations_with_replacement()p, rr-length tuples, in sorted order, with repeated elements
product(‘ABCD’, repeat=2)类似AnnAA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permutations(‘ABCD’, 2)类似A2nAB AC AD BA BC BD CA CB CD DA DB DC
combinations(‘ABCD’, 2)类似C2nAB AC AD BC BD CD
combinations_with_replacement(‘ABCD’, 2)C2n+AA…DDAA 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),关于函数默认参数赋值问题,基本上原则是默认赋值的放后面,否则要在调用函数时使用形参
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python