14、内置函数
第十节 内置函数
help函数可以用来查看函数的用法
help(range)
#输出结果
Help on built-in function range in module __builtin__:
range(...)
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
常用函数
abs(number)
: 绝对值max(iterable[, key=func])
: 最大值min(iterable[, key=func])
: 最小值len(collection)
: 取得一个序列或集合的长度divmod(x, y)
: 求两个数的商和模,返回一个元组(x//y, x%y)pow(x, y[, z])
: 求一个数的幂运算round(number[, ndigits])
: 对一个数进行指定精度的四舍五入callable(object)
: 判断一个对象是否可调用isinstance(object, class-or-type-or-tuple)
:判断对象是否为某个类的实例cmp(x, y)
: 比较两个数或字符串大小range(start [,stop, step])
: 返回一个范围数组,如range(3), 返回[0,1,2]xrange(start [,stop, step])
: 作用与range相同,但是返回一个xrange生成器,当生成范围较大的数组时,用它性能较高
类型转换函数
-
type()
type(object) -> the object's type type(name, bases, dict) -> a new type
-
int()
int(x=0) -> int or long int(x, base=10) -> int or long
-
long()
long(x=0) -> long long(x, base=10) -> long
-
float()
float(x) -> floating point number
-
complex()
complex(real[, imag]) -> complex number
-
str()
str(object='') -> string
-
list()
list() -> new empty list list(iterable) -> new list initialized from iterable's items
-
tuple()
tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items
-
hex()
hex(number) -> string
-
oct()
oct(number) -> string
-
chr()
chr(i) -> character
-
ord()
ord(c) -> integer
string函数
-
str.capitalize()
>>> s = "hello" >>> s.capitalize() 'Hello'
-
str.replace()
>>> s = "hello" >>> s.replace('h', 'H') 'Hello'
-
str.split()
>>> ip = "192.168.1.123" >>> ip.split('.') ['192', '168', '1', '123']
序列处理函数
-
len()
>>>l = range(10) >>> len(l) 10
-
max()
>>>l = range(10) >>> max(l) 9
-
min()
>>>l = range(10) >>> min(l) 0
-
filter()
>>>l = range(10) >>> filter(lambda x: x>5, l) [6, 7, 8, 9]
-
zip()
>>> name=['bob','jack','mike'] >>> age=[20,21,22] >>> tel=[131,132] >>> zip(name, age) [('bob', 20), ('jack', 21), ('mike', 22)] >>> zip(name,age,tel) [('bob', 20, 131), ('jack', 21, 132)] #如果个数不匹配会被忽略
-
map()
>>> map(None, name, age) [('bob', 20), ('jack', 21), ('mike', 22)] >>> map(None, name, age, tel) [('bob', 20, 131), ('jack', 21, 132), ('mike', 22, None)] #个数不匹配时,没有值的会被None代替 >>> a = [1,3,5] >>> b = [2,4,6] >>> map(lambda x,y:x*y, a, b) [2, 12, 30]
-
reduce()
>>> reduce(lambda x,y:x+y, range(1,101)) 5050
lambda -> 列表表达式
-
map的例子,可以写成
print map(lambda x:x*2+10, range(1,11)) print [x*2+10 for x in range(1,11)]
-
非常的简洁,易懂。filter的例子可以写成:
print filter(lambda x:x%3==0, range(1,11)) print [x for x in range(1,11) if x%3 == 0]