python内置函数实例介绍
转载自:
http://mitnk.com/wiki/207/
abs(x) 返回一个数字的绝对值,如果是复数返回其大小
all(iterable) 如果iterable里所有元素都为真,则返回True,否则返回False
any(iterable) 只要iterable里任何一个元素为真,就返回True,否则False
bin(x) 把一个数字转换为二进制字符串 New in Python 2.6
bool([x]) 将一个值转换为布尔型
bytearray([source[, encoding[, errors]]]) 返回一个字节数组
callable(object) 如果object是callable的,返回True,否则False
basestring()
This abstract type is the superclass for str and unicode. It cannot be called or instantiated, but it can be used to test whether an object is an instance of str or unicode. isinstance(obj, basestring) is equivalent to isinstance(obj, (str, unicode)).
chr(i) 输入一个ASCII数值(0-255),输出其字符形式
classmethod(function) classmethod装饰器
cmp(x, y) 当x < y, x == y, x > y时,分别返回 -1, 0, 1
complex([real[, imag]]) 构造一个复数
delattr(object, name) 删除object的一个属性
dict([arg]) 构造一个字典类型
dir([object]) 输出当前作用域的可用数据,或object的所有属性
divmod(a, b) 把两个数字当作参数,返回两个数字的商和余数组成的值对
enumerate(seq[, start=0]) 返回由 (0, seq[0]), (1, seq[1]), (2, seq[2]), ... 组成的枚举
1 for i,j in enumerate([4, 5, 6]): 2 print i,j
输出:
0 4
1 5
2 6
for i,j in enumerate([4,5,6], 2): print i,j
2 4
3 5
4 6
eval(expression[, globals[, locals]]) 计算expression的值,(在globals和locals的基础上)。
1 print eval('x+1',{'x':3}) ##4
1 scope = {} 2 scope['x'] = 2 3 scope['y'] = 3 4 eval('x*y', scope) #6 5 6 scope = {} 7 exec 'x = 3' in scope 8 eval('x*x', scope) #9
exec
1 exec 'print "hello,world"' ##hello,world 2 3 from math import sqrt 4 exec 'sqrt = 1' 5 sqrt(4) 6 Traceback (most recent call last): 7 File "<pyshell#63>", line 1, in <module> 8 sqrt(4) 9 TypeError: 'int' object is not callable 10 11 scope = {} 12 exec 'sqrt = 1' in scope 13 sqrt(4) ##2 14 15 len(scope) ##2 16 scope.keys() ##['__builtins__', 'sqrt']
execfile(filename[, globals[, locals]]) 和exec类似,执行一个文件内的python语句
file(filename[, mode[, bufsize]]) 和open一样打开一个文件,但推荐用open
filter(function, iterable) 表达式 [item for item in iterable if function(item)] 的函数形式
1 print filter(lambda x:x>0, [1, 2, -1, -12, 4])
输出:
[1, 2, 4]
float([x]) 把一个数字或字符串转换为一个浮点数
format(value[, format_spec])
1 print '{0}a{1}b{0}c{2}d{0}'.format(1,2,2)
输出:
'1a2b1c2d1'
getattr(obj, name[, default]) 获取对象的一个属性值
globals() 返回一个字典,包含当前域可用符号表
1 para = 4 2 def show_para(para): 3 print para + globals()['para'] 4 5 show_para(6) ##10
global全局变量
1 x = 1 2 def change_global(): 3 global x 4 x += 1 5 6 change_global() 7 print x ##2
hasattr(obj, name) 查看obj是否有name这个属性,是则返回True
hash(obj) 返回obj的hash值(一个数字)
hex(x) 转换一个数字为其十六进制字符串
1 print hex(12)
输出:
'0xc'
id(obj) 返回obj的标识值
input([prompt]) 和 eval(raw_input(prompt)) 一样
int([x[, base]]) 转换x为int型
isinstance(obj, classinfo) 查看obj是否为classinfo类型的
1 print isinstance(2, int)
结果:
True
issubclass(class, classinfo) 查看class是否是classinfo的子类
iter(o[, sentinel])从可迭代对象中获得迭代器
1 it = iter([1, 2, 3]) 2 it.next() ##1 3 it.next() ##2
len(s) 返回s的长度(元素的个数)
list([iterable]) 将iterable转化为list类型
1 print list((1,))
输出:
[1]
1 print list('hello')
输出
['h', 'e', 'l', 'l', 'o']
locals() 返回描述当前标识表的字典
long([x[, base]]) 将一个字符串或数字转化为一个长整数
map(fun, iterable, ...) 对iterable每个元素应用fun函数后返回结果
1 print map(lambda x,y:x+y, [1, 2, 3],[1, 2, 3])
输出:
[2, 4, 6]
max(iterable[, args ...][, key]) 返回iterable中最大的元素;如果参数是多个数值,则返回最大的
1 max([1,2,3]) 2 max(1,2,3)
memoryview(obj) 返回obj的MemoryView对象
min(iterable[, args...][, key]) 与max相烦,只是返回最小的元素
next(itrator[, default]) 调用itrator的next方法,返回其值
oct(x) 将一个数字转换为一个十进制字符串
open(filename[, mode[, bufsize]]) 打开一个文件,返回这个文件对象
ord(c) 与chr相反,提供一个字符,返回其Unicode数值
pow(x, y[, z]) 返回x的y次方,并对z取模
range([start], stop[, step]) 根据起始条件生成一个list
raw_input([prompt])
reduce(fun, iterable[, initializer]) 将iterable中的元素,通过fun(两参函数)累加起来
1 print reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
输出:
15 ((((1+2)+3)+4)+5)
reload(module) 重新加载一个库
repr(obj) 返回一个obj的可打印形式,和``操作符一样
reversed(sed) 返回seq的反向itrator
1 x = [1, 2, 3] 2 3 print list(reversed(x)) 4 5 [3, 2, 1]
1 x = [1, 2, 3] 2 print reversed(x) 3 <listreverseiterator object at 0x012E42D0>
round(x[, n]) 返回x的n位小数精度的浮点数
set([iterable]) 将iterable转化为set
setattr(obj, name, value) 给obj增加一个值为value名为name的属性
slice([start], stop[, step]) 返回range()相对的一个slice对象
sorted(iteralbe[, cmp[, key[, reverse]]]) 返回对iterable已经排好序的list
1 print sorted('Python') 2 3 ['P', 'h', 'n', 'o', 't', 'y'] 4 5 x = [4,1,3] 6 7 y = sorted(x) 8 9 print y,x 10 11 [1, 3, 4] 12 13 [4, 1, 3]
1 y = ['a', 'wea', 'wq'] 2 print sorted(y, key=len) 3 ['a', 'wq', 'wea'] 4 5 t = [3, 1, 2] 6 print sorted(t, reverse=True) 7 [3, 2, 1]
staticmethod(function) 返回function的静态形式
str([obj]) 返回obj的可打印的字符串形式
sum(iterable[, start]) 返回iterable中的元素累加值
super(type[, obj-or-type]) 返回一个父类或兄弟类的对象代理(只在new style class里才有用) 例子: class C(B): def method(self, arg): super(C, self).method(arg)
tuple([iterable]) 将iterable转化为tuple类
1 print tuple([1, 2, 3]) 2 (1, 2, 3) 3 print tuple('abc') 4 ('a', 'b', 'c') 5 42, 6 (42,)
type(object) 返回object的类型
unichr(i) 返回一个Unicode code是i的Unicode字符
unicode([obj[, encoding[, errors]]]) 返回obj的Unicode字符串
vars([obj]) 返回包含obj的所有属性及其值的字典
zip([iterable, ...]) 返回一个list,其中依次包括每个iterable的元素组成的元组
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
print zipped
((1, 4), (2, 5), (3, 6))
x2, y2 = zip(*zipped)
print x2, y2
(1, 2, 3) (4, 5, 6)
dict()
- dict(one=1, two=2)
- dict({'one': 1, 'two': 2})
- dict(zip(('one', 'two'), (1, 2)))
- dict([['two', 2], ['one', 1]])
- dict((('one', 1), ('two', 2)))
property()
1 class Rectangle(object): 2 def __init__(self): 3 self.width = 0 4 self.length = 0 5 def set_size(self, size): 6 self.width, self.length = size 7 def get_size(self): 8 return self.width, self.length 9 size = property(get_size, set_size) 10 11 r = Rectangle() 12 r.size ##(0, 0) 13 r.size = 12, 2 14 r.size ##(12, 2) 15 r.width = 8 16 r.size ##(8, 2)
apply(func, args[,kwargs])
等同于:func(*args, **keywords),其中:
the args argument must be a sequence
If the optional keywords argument is present, it must be a dictionary whose keys are strings
1 print apply(int, ('100',)) 2 100
浙公网安备 33010602011771号