Python提供了以下几个内置tools模块:operator collections itertools functools
发布日期:2021-06-30 22:47:00 浏览次数:2 分类:技术文章

本文共 4965 字,大约阅读时间需要 16 分钟。

-operator : 内置的操作符模块 
-collections : 简化容器类型的一些操作和使用 
-itertools : 可迭代类型工具 
-functools : 函数工具,尤其是装饰器

operator

operator提供了一个函数与符号的相互转换,方便我们在编程时选择: 
examples 
(1)符号转函数: 
比如在一些需要某些符号功能,却需要提供该符号的函数表示时,尤其是在map reduce filter等的key 和cmp里面

from operator import addprint reduce(add,range(10)) 
1
2
1
2

(2)函数转符号: 
这个例子有点特别,但是在类定义中常见,add->__add__这种方式差别跟的变量有关。 
附:变量命名方式(来自网络): 
 
下面是python符号函数映射表

class A():    def __init__(self,num):        self.num=num    def __add__(self,other):        return self.num+other.num 
1
2
3
4
5
1
2
3
4
5
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)

关于细节内容可以参考 

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 namedtuplemytuple=namedtuple('mytuple',('name','age')])first=mytuple('tom',19)print first.name,first.age 
1
2
3
4
1
2
3
4

这种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 
1
2
3
4
5
6
1
2
3
4
5
6

返回一个字典的子类,键值为可迭代对象里的对象和相应数量。 
对于这个字典里没有的键,返回0,类似于普通字典的 d.get(‘SH’,0) 
关于这种类型的其他方法也可参考官方文档,讲得很清楚。 
OrderedDict 
有序字典,字典中的键按序排放,加入了一些与顺序有关的操作,比如popitem()等 
defaultdict 
对于一个defaultdict类型,当你去访问它的键值时,如果没有这个键,它会调用一个可调用对象,将返回值赋给这个键。

call1 = intcall2 = listcall3 = lambda :4from colletions import defaultdictmydict1 = defaultdict(call1)mydict2 = defaultdict(call2)mydict3 = defaultdict(call3) print mydict1['not'],mydict2['not'],mydict3['not']# OUT : 0 [] 4# 执行过程是,去取这个键的值,如果没有,调用call1(None),...# 如果你想知道我说的对不对,可以把call3 = lambda x:4 ,试试,看他的报错就知道了。 
1
2
3
4
5
6
7
8
9
10
11
1
2
3
4
5
6
7
8
9
10
11

colletions后面还列出了一些类,用于继承和isinstance判断 
本节参考: 

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 AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permutations(‘ABCD’, 2) 类似 A2n AB AC AD BA BC BD CA CB CD DA DB DC
combinations(‘ABCD’, 2) 类似 C2n AB AC AD BC BD CD
combinations_with_replacement(‘ABCD’, 2) C2n +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 partialdef basefunc(a,b):    return a+bnewfunc = partial(basefunc,b=1)print newfunc(5)# OUT : 6#这里要考虑函数默认参数的问题,如果newfunc = partial(basefunc,a=1),print 时会报错,必须print new

转载地址:https://lqfarmer.blog.csdn.net/article/details/73332169 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:模型汇总15 领域适应性Domain Adaptation、One-shot/zero-shot Learning概述
下一篇:Python学习4:生成器、lamda表达式及map、reduce、filter函数

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月06日 18时38分14秒