内建函数

Build-in Function,启动python解释器,输入dir(__builtins__), 可以看到很多python解释器启动后默认加载的属性和函数,这些函数称之为内建函数, 这些函数因为在编程时使用较多,cpython解释器用c语言实现了这些函数,启动解释器 时默认加载。

这些函数数量众多,不宜记忆,开发时不是都用到的,待用到时再help(function), 查看如何使用,或结合百度查询即可,在这里介绍些常用的内建函数。

range

    range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
  • start:计数从start开始。默认是从0开始。例如range(5)等价于range(0, 5);
  • stop:到stop结束,但不包括stop.例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
  • step:每次跳跃的间距,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)

python2中range返回列表,python3中range返回一个迭代值。如果想得到列表,可通过list函数

a = range(5)
list(a)

创建列表的另外一种方法

In [21]: testList = [x+2 for x in range(5)]

In [22]: testList
Out[22]: [2, 3, 4, 5, 6]

map函数

map函数会根据提供的函数对指定序列做映射

    map(...)
map(function, sequence[, sequence, ...]) -> list
  • function:是一个函数
  • sequence:是一个或多个序列,取决于function需要几个参数
  • 返回值是一个list

参数序列中的每一个元素分别调用function函数,返回包含每次function函数返回值的list。

#函数需要一个参数
map(lambda x: x*x, [1, 2, 3])
#结果为:[1, 4, 9] #函数需要两个参数
map(lambda x, y: x+y, [1, 2, 3], [4, 5, 6])
#结果为:[5, 7, 9] def f1( x, y ):
return (x,y) l1 = [ 0, 1, 2, 3, 4, 5, 6 ]
l2 = [ 'Sun', 'M', 'T', 'W', 'T', 'F', 'S' ]
l3 = map( f1, l1, l2 )
print(list(l3))
#结果为:[(0, 'Sun'), (1, 'M'), (2, 'T'), (3, 'W'), (4, 'T'), (5, 'F'), (6, 'S')]

filter函数

filter函数会对指定序列执行过滤操作

filter(...)
filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.
  • function:接受一个参数,返回布尔值True或False
  • sequence:序列可以是str,tuple,list

filter函数会对序列参数sequence中的每个元素调用function函数,最后返回的结果包含调用结果为True的元素。

返回值的类型和参数sequence的类型相同

返回值的类型和参数sequence的类型相同

filter(lambda x: x%2, [1, 2, 3, 4])
[1, 3] filter(None, "she")
'she'

reduce函数

reduce函数,reduce函数会对参数序列中元素进行累积

reduce(...)
reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
  • function:该函数有两个参数
  • sequence:序列可以是str,tuple,list
  • initial:固定初始值

reduce依次从sequence中取一个元素,和上一次调用function的结果做参数再次调用function。 第一次调用function时,如果提供initial参数,会以sequence中的第一个元素和initial 作为参数调用function,否则会以序列sequence中的前两个元素做参数调用function。 注意function函数不能为None。

reduce(lambda x, y: x+y, [1,2,3,4])
10 reduce(lambda x, y: x+y, [1,2,3,4], 5)
15 reduce(lambda x, y: x+y, ['aa', 'bb', 'cc'], 'dd')
'ddaabbcc'

在Python3里,reduce函数已经被从全局名字空间里移除了, 它现在被放置在fucntools模块里用的话要先引入: from functools import reduce

sorted函数

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

集合set

集合与之前列表、元组类似,可以存储多个数据,但是这些数据是不重复的

集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric_difference(对称差集)等数学运算.

>>> x = set('abcd')
>>> x
{'c', 'a', 'b', 'd'}
>>> type(x)
<class 'set'>
>>>
>>>
>>> y = set(['h','e','l','l','o'])
>>> y
{'h', 'e', 'o', 'l'}
>>>
>>>
>>> z = set('spam')
>>> z
{'s', 'a', 'm', 'p'}
>>>
>>>
>>> y&z #交集
set()
>>>
>>>
>>> x&z #交集
{'a'}
>>>
>>>
>>> x|y #并集
{'a', 'e', 'd', 'l', 'c', 'h', 'o', 'b'}
>>>
>>> x-y #差集
{'c', 'a', 'b', 'd'}
>>>
>>>
>>> x^z #对称差集(在x或z中,但不会同时出现在二者中)
{'m', 'd', 's', 'c', 'b', 'p'}
>>>
>>>
>>> len(x)
4
>>> len(y)
4
>>> len(z)
4
>>>

functools

functools 是python2.5被引人的,一些工具函数放在此包里。

python2.7中

python3.5中

import functools
dir(functools)

运行结果:

['MappingProxyType',
'RLock',
'WRAPPER_ASSIGNMENTS',
'WRAPPER_UPDATES',
'WeakKeyDictionary',
'_CacheInfo',
'_HashedSeq',
'__all__',
'__builtins__',
'__cached__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'_c3_merge',
'_c3_mro',
'_compose_mro',
'_convert',
'_find_impl',
'_ge_from_gt',
'_ge_from_le',
'_ge_from_lt',
'_gt_from_ge',
'_gt_from_le',
'_gt_from_lt',
'_le_from_ge',
'_le_from_gt',
'_le_from_lt',
'_lru_cache_wrapper',
'_lt_from_ge',
'_lt_from_gt',
'_lt_from_le',
'_make_key',
'cmp_to_key',
'get_cache_token',
'lru_cache',
'namedtuple',
'partial',
'partialmethod',
'reduce',
'singledispatch',
'total_ordering',
'update_wrapper',
'wraps']

python3中增加了更多工具函数,做业务开发时大多情况下用不到,此处介绍使用频率较高的2个函数。

partial函数(偏函数)

把一个函数的某些参数设置默认值,返回一个新的函数,调用这个新函数会更简单。

import functools

def showarg(*args, **kw):
print(args)
print(kw) p1=functools.partial(showarg, 1,2,3)
p1()
p1(4,5,6)
p1(a='python', b='itcast') p2=functools.partial(showarg, a=3,b='linux')
p2()
p2(1,2)
p2(a='python', b='itcast')

wraps函数

使用装饰器时,有一些细节需要被注意。例如,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变)。

添加后由于函数名和函数的doc发生了改变,对测试结果有一些影响,例如:

def note(func):
"note function"
def wrapper():
"wrapper function"
print('note something')
return func()
return wrapper @note
def test():
"test function"
print('I am test') test()
print(test.__doc__)

运行结果

note something
I am test
wrapper function

所以,Python的functools包中提供了一个叫wraps的装饰器来消除这样的副作用。例如:

import functools
def note(func):
"note function"
@functools.wraps(func)
def wrapper():
"wrapper function"
print('note something')
return func()
return wrapper @note
def test():
"test function"
print('I am test') test()
print(test.__doc__)

运行结果

note something
I am test
test function

内建函数(builtins)和functools的更多相关文章

  1. 类装饰器,元类,垃圾回收GC,内建属性、内建方法,集合,functools模块,常见模块

    '''''''''类装饰器'''class Test(): def __init__(self,func): print('---初始化---') print('func name is %s'%fu ...

  2. python3中内建函数map()与reduce()的使用方法

    map()的使用    map()的使用方法形如map(f(x),Itera).对,它有两个参数,第一个参数为某个函数,第二个为可迭代对象.如果不懂什么是函数,不懂什么是可迭代对象没关系,记住下面的例 ...

  3. Python 常用的内建函数

    内建函数 ​ Build-in Function,启动python解释器,输入dir(__builtins__), 可以看到很多python解释器启动后默认加载的属性和函数,这些函数称之为内建函数, ...

  4. 13 内建属性 _getattribute_ 内建函数

    1.内建属性 2.__getattribute__ 属性访问时拦截器 class Itcast(object): def __init__(self,subject1): self.subject1 ...

  5. Python的程序结构[5] -> 模块/Module[0] -> 内建模块 builtins

    builtins 内建模块 / builtins Module 在Python的模块中,有一种特殊模块,无需导入便可以使用,其中包含了许多内建函数与类. builtins 模块内容 / builtin ...

  6. builtins内建模块

    builtins模块 为啥我们没有导入任何模块就能使用len(),str(),print()...等这么多的函数? 其实在我们运行python解释器的时候,他会自动导入一些模块,这些函数就是从这些地方 ...

  7. functools模块

    from functools import wraps def logged(func):     @wraps(func)     def with_logging(*args, **kwargs) ...

  8. (转)论python工厂函数与内建函数

    所谓工厂函数就是指这些内建函数都是类对象, 当你调用它们时,实际上是创建了一个类实例.   工厂函数: int(),long(),float(),complex(),bool() str(),unic ...

  9. Python标准模块--functools

    1 模块简介 functools,用于高阶函数:指那些作用于函数或者返回其它函数的函数,通常只要是可以被当做函数调用的对象就是这个模块的目标. 在Python 2.7 中具备如下方法, cmp_to_ ...

随机推荐

  1. URL的应用

    1.对于Android来说,开发应用都会去访问服务器地址,那么就要连网,需要通过URL. 先new一个URL来获取路径,然后利用HttpURLConnection来连接并打开url,并通过get 请求 ...

  2. linux中grep用法(“或”、“与”)

    1.普通用法 grep keyword 若果keyword中有空格 grep "keyword" 例如: ls | grep mp4 2.“与”操作(其实就是多次筛选) grep ...

  3. 在 Roslyn 分析语法树时添加条件编译符号的支持

    我们在代码中会写 #if DEBUG 或者 [Conditional("DEBUG")] 来使用已经定义好的条件编译符号.而定义条件编译符号可以在代码中使用 #define WAL ...

  4. HDU 2108 逆时针给出多边形的顶点,判断是否为凸多边形,水题

    下面是别人解题报告的链接,很详细,写的很好 http://blog.csdn.net/chl_3205/article/details/8520597 下面贴我的代码 #include <cst ...

  5. hdu2085-2086

    hdu2085 模拟 #include<stdio.h> ][]; void fun(){ a[][]=; a[][]=; ;i<=;i++){ a[i][]=*a[i-][]+*a ...

  6. 12 Factor CLI Apps

    CLIs are a fantastic way to build products. Unlike web applications, they take a small fraction of t ...

  7. apache flink docker-compose 运行试用

    apache 是一个流处理框架,官方提供了docker 镜像,同时也提供了基于docker-compose 运行的说明 docker-compose file version: "2.1&q ...

  8. search bar 创建的一些文章

    1.   http://blog.csdn.net/oscarxie/article/details/1434608 2.   http://blog.csdn.net/oscarxie/articl ...

  9. oracle 无法启动图形界面,no protocol specified

    linux 终端启动图形化程序界面时报错:No protocol specified这是因为Xserver默认情况下不允许别的用户的图形程序的图形显示在当前屏幕上. 如果需要别的用户的图形显示在当前屏 ...

  10. JS时间(日期)比较或相减(暂时停用)

    注:此文均来自网上,可行,只供参考 //JAVASCRIPT中 日期相减很麻烦 ,现在有现成的实现方法,拷贝过去就可以用了,方便 //调用该方法(主方法) function dateDiff(date ...