python 内建方法

 

文档


 http://python.usyiyi.cn/translate/python_278/library/functions.html

内建方法


运算相关

  • abs(x)

返回一个数的绝对值。参数可以是普通的整数,长整数或者浮点数。如果参数是个复数,返回它的模。

In [4]: abs(1.234)
Out[4]: 1.234

In [5]: abs(-1.234)
Out[5]: 1.234
  • cmp(x, y)

比较两个对象x和y,根据结果返回一个整数。如果y,返回负数;如果== y,返回0;如果y,返回正数。

In [7]: cmp(1.11, 1.12)
Out[7]: -1

In [8]: cmp(1.12, 1.11)
Out[8]: 1

In [9]: cmp(-1.11, -1.12)
Out[9]: 1

In [10]: cmp(1, 1)
Out[10]: 0
  • divmod(a, b)

在长整数除法中,传入两个数字(非复数)作为参数,返回商和余数的二元组。

In [11]: divmod(5, 2)
Out[11]: (2, 1)
  • max(iterable[, key])

  • max(arg1, arg2, *args[, key])

返回可迭代的对象中的最大的元素,或者返回2个或多个参数中的最大的参数。

In [12]: max(1, 1.1, 1.2)
Out[12]: 1.2

In [13]: max([1, 1.1, 1.2])
Out[13]: 1.2

In [14]: max((1, 1.1, 1.2))
Out[14]: 1.2

In [15]: max('12')
Out[15]: '2'
  • min(iterable[, key])
  • min(arg1, arg2, *args[, key])

返回可迭代的对象中的最小的元素,或者返回2个或多个参数中的最小的参数。

  • pow(x, y[, z])

返回x 的 y次幂; 如果 z 提供的时候,, 返回 x 的 y 次幂,然后对  z 取模。

In [19]: pow(2, 3)
Out[19]: 8

In [20]: pow(2, 3, 6)
Out[20]: 2
  • round(number[, ndigits])

返回一个浮点型 近似值,保留小数点后 ndigits 位。

如果省略ndigits,它默认为零。结果是一个浮点数。数值被四舍五入为功率减去ndigits的最接近的倍数10。如果有两个倍数离的一样近,结果取离0较远的。 

In [1]: round(1.1234567, 4)
Out[1]: 1.1235

In [2]: round(1.1234567, 3)
Out[2]: 1.123

In [3]: round(-1.1234567, 3)
Out[3]: -1.123

In [4]: round(1.1234567, 4)
Out[4]: 1.1235

In [5]: round(2.765, 2)
Out[5]: 2.77
  • sum(iterable[, start])

将start以及iterable的元素从左向右相加并返回总和。start默认为0

iterable的元素通常是数字,start值不允许是一个字符串。

In [9]: sum([1, 2, 3])
Out[9]: 6

In [10]: sum([1, 2, 3], 4)
Out[10]: 10

In [11]: sum(4, [1, 2, 3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-ce50faac39a9> in <module>()
----> 1 sum(4, [1, 2, 3])

TypeError: 'int' object is not iterable

数据类型相关

int

float

long

str

complex

ord

chr

unichr

bool

bin

hex

oct

list

tuple

slice

dict

repr

compile

eval

exec

元组、列表相关

all

any

sorted

reversed

字段、对象相关

hasattr

getattr

setattr

delattr

isinstance

issubclass

其他

input

globals

locals

 

posted @ 2017-07-06 23:16  Meow-z  阅读(252)  评论(0编辑  收藏  举报