python中的库函数_python中常用的函数与库一

1, collections.deque

在python里如果我们用列表作为队列使用也是可以的,只是当从队尾删除或者增加元素的时候是很快的,但是从队首删除或者增加元素则要慢得多,这是因为在队首进行操作其他的元素都要逐一改变。

collections.deque就是为队列设计的,它能迅速得删除或者增加元素,无论是队首还是队尾

>>> from collections import deque

>>> queue = deque(["Eric", "John", "Michael"])

>>> queue.append("Terry") # Terry arrives

>>> queue.append("Graham") # Graham arrives

>>> queue.popleft() # The first to arrive now leaves

'Eric'

>>> queue.popleft() # The second to arrive now leaves

'John'

>>> queue # Remaining queue in order of arrival

deque(['Michael', 'Terry', 'Graham'])

2, filter() map() reduce()

filter(function,sequence) 返回一个function(item)为True的序列,当sequence为string的时候,也会返回与string编码相同的字符序列

>>> def f(x): return x % 3 == 0 or x % 5 == 0

...

>>> filter(f, range(2, 25))

[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

>>> def f(x):return x == 'a' or x=='b'

...

>>>filter(f, 'abfsagdcb')

'abab'

map(function,sequence) 会将sequence里的每个元素依次作为参数调用function(item),它会将function(item)的返回值放入列表再返回

>>> def cube(x): return x*x*x

...

>>> map(cube, range(1, 11))

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

map(function,sequence,sequence) 当传入多个序列时,他会依次从每个序列中取出一个元素作为参数调用function(item1,item2),如果序列之间的元素个数不一样,则会在较短的序列中默认添加None作为参数传入

>>> seq = range(8)

>>> def add(x, y): return x+y

...

>>> map(add, seq, seq)

[0, 2, 4, 6, 8, 10, 12, 14]

>>>seq2 = range(7)

>>>map(add, seq, seq2)

Traceback (most recent call last):

File "", line 1, in

File "", line 1, in add

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

reduce(function,sequence) 只返回一个迭代值,第一次传入两个元素到function(item1,item2),之后将result作为一个参数传入并且再从sequence中取出1个元素传入function中,以此类推

>>> def add(x,y): return x+y

...

>>> reduce(add, range(1, 11))

55

reduce(function,sequence,init_value) reduce也可以有第三个参数,第三个参数是reduce的初始化值,也就是第一个传入function的值,当然如果sequence是个空序列的话我们也可以让第三个参数为0这样reduce返回的也会是0

>>>def add(x, y):return x+y

>>>reduce(add, range(1,11), 10)

65

>>>reduce(add, [],0)

0

>>>reduce(add, [],10)

10

3, enumerate() zip() del()

enumerate(sequence)可以在序列中加上索引,例如:

>>> for i, v in enumerate(['tic', 'tac', 'toe']):

... print i, v

...

0 tic

1 tac

2 toe

zip(sequence1,sequence2) 会从多个序列中依次取出一个值打包成另一个元组,返回多个由元组构成的列表,当sequence长度不一致时以长度最小的序列作为标准,zip(*matrix)也可以传入一个列表

>>> zip([1,2,3],[1,2,3])

[(1, 1), (2, 2), (3, 3)]

...

>>> zip([1,2,3],[1,2,3],[1,2,3])

[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

...

>>> zip([1,2,3],[1,2,])

[(1, 1), (2, 2)]

>>> matrix = [

... [1, 2, 3, 4],

... [5, 6, 7, 8],

... [9, 10, 11, 12],

... ]

>>> zip(*matrix)

[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

del() 函数可以移除列表中的元素,以及某个变量

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]

>>> del a[0]

>>> a

[1, 66.25, 333, 333, 1234.5]

>>> del a[2:4]

>>> a

[1, 66.25, 1234.5]

>>> del a[:]

>>> a

[]

...

>>> del a

>>>a

Traceback (most recent call last):

File "", line 1, in

NameError: name 'a' is not defined

4, set() 用于创建集合,如下所示集合的一些操作:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']

>>> fruit = set(basket) # create a set without duplicates

>>> fruit

set(['orange', 'pear', 'apple', 'banana'])

>>> 'orange' in fruit # fast membership testing

True

>>> 'crabgrass' in fruit

False

>>> # Demonstrate set operations on unique letters from two words

...

>>> a = set('abracadabra')

>>> b = set('alacazam')

>>> a # unique letters in a

set(['a', 'r', 'b', 'c', 'd'])

>>> a - b # letters in a but not in b

set(['r', 'd', 'b'])

>>> a | b # letters in either a or b

set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])

>>> a & b # letters in both a and b

set(['a', 'c'])

>>> a ^ b # letters in a or b but not both

set(['r', 'd', 'b', 'm', 'z', 'l'])

5, sorted() reversed() sort() reverse()

sort()是可变对象(列表)的方法,无参数,无返回值,sort()会改变可变对象,因此无需返回值。sort()方法是可变对象独有的方法或者属性,而作为不可变对象如元组、字符串是不具有这些方法的,如果调用将会返回一个异常。

sorted()是python的内置函数,并不是可变对象(列表、字典)的特有方法,sorted()函数需要一个参数(参数可以是列表、字典、元组、字符串),无论传递什么参数,都将返回一个以列表为容器的返回值,如果是字典将返回键的列表。

reverse()与sort()的使用方式一样,而reversed()与sorted()的使用方式相同

>>> sorted([1,2,3])

[1, 2, 3]

>>> reversed([1,2,3])

>>> for i in reversed([1,2,3]):print i

3

2

1

...

>>> a = [2,3,1]

>>> a.sort()

>>> a

[1, 2, 3]

>>> a.reverse()

>>> a

[3, 2, 1]

6, __all__

__all__ = ['echo','company','employee'] 可以放在__init__文件中当使用 from xxx import * 时将导入__all__中指定的模块

7, str.format(*args, **kwargs)

str.format是格式化字符串的一种方式,用法比较简单直接上代码:该例中{!s}和{!r}指的是分别用str()和repr()处理,函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式

>>> print 'hello you are smart,{0}{1}'.format('Steven','Daole')

hello you are smart,StevenDaole

...

>>> print 'hello you are smart,{name}'.format(name='Jack')

hello you are smart,Jack

...

通过对象属性

>>>import math

>>>print '{.pi}'.format(math)

3.14159265359

通过下标

>>>p = [1,2]

>>>print '{0[0]},{0[1]}'.format(p)

1,2

>>> print '{.pi!s}'.format(math)

3.14159265359

>>> print '{.pi!r}'.format(math)

3.141592653589793

填充常跟对齐一起使用

^、分别是居中、左对齐、右对齐,后面带宽度

:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充

>>> '{:>8}'.format('189')

' 189'

>>> '{:0>8}'.format('189')

'00000189'

>>> '{:a>8}'.format('189')

'aaaaa189'

精度常跟类型f一起使用,其中.2表示长度为2的精度,f表示float类型。b、d、o、x分别是二进制、十进制、八进制、十六进制。

>>> '{:.2f}'.format(321.33345)

'321.33'

>>> '{:b}'.format(17)

'10001'

>>> '{:d}'.format(17)

'17'

>>> '{:o}'.format(17)

'21'

>>> '{:x}'.format(17)

'11'

用,号还能用来做金额的千位分隔符。

>>> '{:,}'.format(1234567890)

'1,234,567,890'

8,python的Template使用指南

Template无疑是一个好东西,可以将字符串的格式固定下来,重复利用。同时Template也可以让开发人员可以分别考虑字符串的格式和其内容了,无形中减轻了开发人员的压力

Template中有两个重要的方法:substitute和safe_substitute,这两个方法都可以通过获取参数返回字符串

>>s=Template(There $a and $b)

>>print s.subtitute(a='apple',b='banana')

There apple and banana

>>print s.safe_substitute(a='apple',b='banbana')

There apple and banbana

...

还可以通过获取字典直接传递数据,像这样

>>s=Template(There $a and $b)

>>d={'a':'apple','b':'banbana'}

>>print s.substitute(d)

There apple and banbana

Template可以被继承,它的子类可以进行一些‘个性化'操作...通过修改delimiter字段可以将$字符改变为其他字符,如“#”,不过新的标示符需要符合正则表达式的规范。通过修改idpattern可以修改key的命名规则,比如说规定第一个字符开头必须是a,这对规范命名倒是很有好处。当然,这也是通过正则表示实现的。

from string import Template

class MyTemplate(Template):

delimiter = "#"

idpattern = "[a][_a-z0-9]*"

def test():

s='#aa is not #ab'

t=MyTemplate(s)

d={'aa':'apple','ab':'banbana'}

print t.substitute(d)

if __name__=='__main__':

test()

#result:

#apple is not banbana

9, str.rjust() str.ljust() str.zfill()

这三个函数都有只一个参数,该参数是int型指定输出的字符串长度,他们的效果如下,rjust是向右对齐,ljust是向左对齐,zfill是用0填充

>>> 'fdsa'.rjust(10)

' fdsa'

>>> 'fdsa'.ljust(10)

'fdsa '

>>> 'fdsa'.zfill(10)

'000000fdsa'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值