6.7 常用内置函数

Python解释器有许多内置的函数和类型。

内置函数
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed()
complex() hasattr() max() round()

其中一些函数的使用方法如下:

abs(x)

返回数字的绝对值。参数可以是整数或浮点数。

>>> abs(-20)
20

all(iterable)

如果可迭代对象中所有元素都为True,结果为True,否则为False。如果参数为空,返回True。

>>> all([True, True, True])
True
>>> all([True, False, True])
False
>>> all([])
True

any(iterable)

如果可迭代对象中所有元素都为False,结果为False,否则为True。如果参数为空,返回False。

>>> any([True, False, True])
True
>>> any([False, False, False])
False
>>> any([])
False

chr(i)

返回表示Unicode编码值为整数i的字符的字符串。与ord()相反。

>>> chr(97)
'a'
>>> chr(8364)
'€'

参数的有效范围是0到1,114,111(十六进制的0x10FFFF)。如果i超出该范围,将抛出ValueError。

enumerate(iterable, start=0)

返回一个枚举对象。iterable必须是序列,迭代器或支持迭代的其他对象。

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

eval(表达式, globals=None, locals=None)

参数是一个字符串和可选的全局变量和本地变量。分析表达式参数,并作为一个Python表达式来使用。

>>> x = 1
>>> eval('x+1')
2

format(value [, format_spec ])

将value转换为“格式化”表示,由format_spec控制。format_spec的解释取决于value参数的类型,但是大多数内置类型都使用标准格式化语法。

isinstance(object, classinfo)

如果object参数是classinfo参数的实例,或者是(直接,间接或虚拟)子类的实例,则返回true。如果object不是给定类型的对象,则该函数始终返回false。

>>> isinstance([1, 2, 3, 4], list)
True

issubclass(class, classinfo)

如果class是classinfo的子类(直接,间接或虚拟),则返回true。类被认为是其自身的子类。

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

返回可迭代对象中的最大项或多个参数中的最大项。

>>> max(10, 30, 25, 28)
30

min(arg1, arg2, *args [, key ])

返回可迭代对象中的最小项或多个参数中的最小项。

>>> min(10, 30, 25, 28)
10

ord(c)

给定表示一个Unicode字符的字符串,返回表示该字符的Unicode编码值的整数。与chr()相反。

>>> ord('a')
97
>>> ord('€')
8364

pow(x, y [, z ])

返回x的y次幂。

>>> pow(9, 2)
81
>>> pow(16, 0.5)
4.0

reversed(seq)

返回反向迭代器。

>>> list(reversed([1, 3, 6, 2, 4]))
[4, 2, 6, 3, 1]

round(number [, ndigits ])

返回在小数点后舍入到ndigits精度的number。如果ndigits被省略或是None,则返回其输入的最接近的整数。

>>> round(4.2)
4
>>> round(4.8)
5
>>> round(4.5)
4

sorted(iterable, *, key=None, reverse=False)

从iterable中的项返回一个新的排序列表。

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

sum(iterable [, start ])

sum计算iterable的项目并返回总和。

>>> sum([1, 3, 6, 2, 4])
16

zip(*iterables)

创建一个聚合了来自每个迭代的元素的迭代器。

zip()与*运算符一起使用可以解压缩列表:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zp = zip(x, y)
>>> list(zp)
[(1, 4), (2, 5), (3, 6)]

>>> a, b = zip(*[('a', 1), ('b', 2), ('c', 3)])
>>> a
('a', 'b', 'c')
>>> b
(1, 2, 3)