python内置函数

abs

>>> abs(-10)
10
>>> abs(10)
10

>>> l = [1, 3, 5, 2, 4, 10, -1]
>>> abs(l)  #不能对序列求绝对值
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'list'

max和min

>>> l = [1, 3, 5, 2, 4, 10, -1]
>>> max(l)
10
>>> min(l)
-1

len

求字符串、序列或者字段的长度

>>> l = [1, 3, 5, 2, 4, 10, -1]
>>> s = 'hello world'
>>> t = (1, 5, 'welcome')
>>> d = {'key1':10, 'key2':13}
>>> len(l)
7
>>> len(s)
11
>>> len(t)
3
>>> len(d)
2

divmod

divmod(x, y) -> (quotient, remainder)
Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.
根据英文官方文档的解释,返回一个元组,元组的第一个元素是商、第二个元素是余数。

>>> divmod(10, 2)
(5, 0)
>>> divmod(10, 3)
(3, 1)
>>> divmod(8, 3)
(2, 2)
>>> divmod(5, 3)
(1, 2)

pow

pow(x, y[, z]) -> number
With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
函数有两个参数或是三个参数,第三个参数可有可无;当两个参数的时候,代表是x的y次方,三个参数的时候,返回值(x**y) % z

>>> pow(2, 3)
8
>>> pow(2, 3, 4)
0
>>> pow(2, 3, 3)
2

round

round(number[, ndigits]) -> floating point number 返回一个浮点数
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
小数点位数默认显示一位, 保留小数点的时候四舍五入

>>> round(10.12345) # 默认显示一位
10.0
>>> round(10.12345, 1) #
10.1
>>> round(10.12345, 2)
10.12
>>> round(10.12345, 3)
10.123
>>> round(10.12345, 4)
10.1235

callable

callable(object) -> bool
Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances with a call() method.

测试某一对象是否可被调用,通常测试函数;变量返回Flase。如下面的例子:

>>> num1 = 10
>>> callable(num1)
False
>>> def fun(x, y):
...     return x+y
... 
>>> callable(fun)
True

isinstance

isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object’s type.The form using a tuple, isinstance(x, (A, B, …)), is a shortcut for isinstance(x, A) or isinstance(x, B) or … (etc.).
判断某一个对象是否是**类型

#!/usr/bin/python

l = [1, 3, 5]
if type(l) == type([]):
    print "type(l) is list"
else :
    print "type(l) is not list"

print isinstance(l, list)
print '-'*20
s = "hello python"
print isinstance(s, str)

输出结果:
type(l)  is list
True
--------------------
True

cmp

cmp(x, y) -> integer

Return negative if x<y, zero if x==y, positive if x>y.

如果x小于y返回-1,x等于y返回0,x大于y返回1.
可以比较数字、字符串、列表

>>> cmp(1, 1)
0
>>> cmp(1, -1)
1
>>> cmp(1, 3)
-1
>>> cmp("abc", "abd")
-1
>>> cmp(["abc"], ["abd", 1])
-1
>>> cmp(["abc", 3], ["abd", 1])
-1
>>> cmp(["abc", 3], ["abc", 1])
1

range

xrange

你可能感兴趣的:(python,内建函数)