Python 3.6.2 标准库之内置函数

大多数编程语言都有自己的内置函数,Python也不例外,同样提供了丰富的内置函数,其中包括算术函数、字符串操作函数、时间操作相关的函数、位操作函数等。程序开发者不需要进行导入操作就可以使用这些函数。内置函数的存在极大的提升了程序的开发效率。

以下是Python内置函数的一个简单的列表,在后面的内容中会对它们的用法逐个进行讲解。

名称 说明
abs() 返回整数/浮点数的绝对值,如果参数是一个复数,返回复数的积。
all() 如果参数 iterable 的所有元素的值为 true(即元素的值不为0、''、False)或者参数 iterable 为空,all(iterable) 返回 True,否则返回 False。
any() 如果参数 iterable 存在一个元素为 true(即元素的值不为0、''、False),函数 any(iterable) 返回 True,否则返回 False(参数 iterable 为空时也返回 False)。
ascii() 跟函数 repr() 一样返回一个可打印的对象字符串方式表示。如果是非ascii字符就会输出\x,\u或\U等字符来表示。与 Python 2 版本里的 repr() 是等效的函数。
bin() 将整数 x 转换为前缀为“0b”的二进制字符串,如果 x 不为Python中 int 类型,x 必须包含方法 __index__() 并且返回值为integer。
bool() 将 x 转换为布尔值(True 或 False)。如果 x 缺省,返回 False。
bytearray() 返回一个新的字节数组(bytes)对象,数组里的元素是可以被修改的,并且元素的取值范围为 [0, 255]。
bytes() 返回一个新的字节数组(bytes)对象,数组里的元素是不可修改的,并且元素的取值范围为 [0, 255]。
callable() 判断一个对象 object 是否可以被调用。
chr() 返回整数 i 所对应的 Unicode 字符
classmethod() 指定一个类的方法为类方法
compile() 将 source 编译为代码或者AST对象
complex() 返回一个值为 real + imag*j 的复数,或者把字符串或数字转化为复数
delattr() 删除对象 object 中名为 name 的属性
dict() 字典类 dict 的构造函数
dir()
divmod() 计算两个数值相除的商和余数
enumerate() 把可迭代对象转换为枚举对象
eval() 动态执行一个表达式的字符串,或者 compile() 函数编译出来的代码对象
exec() 动态执行 Python 代码。
filter()
float()
format()
frozenset()
getattr()
globals()
hasattr()
hash()
help()
hex()
id()
input()
int()
isinstance()
issubclass()
iter()
len()
list()
locals()
map()
max()
memoryview()
min()
next()
object()
oct()
open()
ord()
pow()
print()
property()
range()
repr()
reversed()
round()
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()
tuple()
type()
vars()
zip()
__import__()

内置函数使用示例

abs(x)

返回整数/浮点数的绝对值,如果参数是一个复数,返回复数的积。

示例

下面的示例使用 abs(x) 方法以获取数的绝对值。

>>> abs(-1)
1
>>> abs(-2.35)
2.35
>>> abs(8)
8
>>> a=20-9j
>>> a.real
20.0
>>> a.imag
-9.0
>>> abs(a.real)
20.0
>>> abs(a.imag)
9.0
>>> abs(a)
21.93171219946131

all(iterable)

如果参数 iterable 的所有元素的值为 true(即元素的值不为0、''、False)或者参数 iterable 为空,all(iterable) 返回 True,否则返回 False。

说明:参数 iterable 是可迭代对象。

该函数等价于:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

示例

下面的代码演示了列表/元组具有不同元素时函数 all(iterable) 的返回值。

>>> all([])     # 空列表
True
>>> all(())     # 空元组
True
>>> all([0, 5]) # 列表存在值为 0 的元素
False
>>> all(['', 'oooop']) # 列表存在空字符串
False
>>> all([False, 'etc', True]) # 列表存在值为 False 的元素
False
>>> all([True, 'iuuuuuuu', 3, -9, '89']) # 列表元素的值都不为 0、''、 False
True
>>> all((0, 5)) # 元组存在值为 0 的元素
False
>>> all(('', 'iuuy')) # 元组元素存在空字符串
False
>>> all((False, 'iwe')) # 元组存在值为 False 的元素
False
>>> all((True, 'iwe', 37, 'u2')) # 元组元素的值都不为 0、''、 False
True

any(iterable)

如果参数 iterable 存在一个元素为 true(即元素的值不为0、''、False),函数 any(iterable) 返回 True,否则返回 False(参数 iterable 为空时也返回 False)。

说明:参数 iterable 是可迭代对象。

该函数等价于:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

示例

下面的代码演示了列表/元组具有不同元素时函数 any(iterable) 的返回值。

>>> any([]) # 空列表
False
>>> any(()) # 空元组
False
>>> any([0, '', False]) # 列表不存在值为 true 的元素
False
>>> any([0, 'iujk', '', False]) # 列表存在一个值为 true 的元素
True
>>> any((0, "", False)) # 元组不存在值为 true 的元素
False
>>> any((0, "", False, 98)) # 元组存在一个值为 true 的元素
True

ascii(object)

跟函数 repr() 一样返回一个可打印的对象字符串方式表示。如果是非ascii字符就会输出\x,\u或\U等字符来表示。与 Python 2 版本里的 repr() 是等效的函数。

示例

>>> ascii(8763)
'8763'
>>> ascii('+&^%$#')
"'+&^%$#'"
>>> ascii('中华民族')
"'\\u4e2d\\u534e\\u6c11\\u65cf'"
>>> ascii('b\31')
"'b\\x19'"
>>> ascii('0x\1000')
"'0x@0'"

bin(x)

将整数 x 转换为前缀为“0b”的二进制字符串,如果 x 不为Python中 int 类型,x 必须包含方法 __index__() 并且返回值为integer。

示例

>>> bin(25)
'0b11001'
>>> bin(-25)
'-0b11001'

# 非整型的情况,必须包含__index__()方法切返回值为integer的类型
>>> class fooType:
...     def __index__(self):
...             return 25
... 
>>> t=fooType()
>>> bin(t)
'0b11001'

bool([x])

将 x 转换为布尔值(True 或 False)。如果 x 缺省,返回 False。

说明:参数 x 可以是任意对象或缺省。

示例

>>> bool(0)
False
>>> bool('')
False
>>> bool([])
False
>>> bool(())
False
>>> bool(432)
True
>>> bool('iopp')
True
>>> bool([0])
True
>>> bool()
False
>>> bool((0, 9))
True


bytearray([source[, encoding[, errors]]])

返回一个新的字节数组(bytes)对象,数组里的元素是可以被修改的,并且元素的取值范围为 [0, 255]。

说明:如果可选参数 source

  • 字符串时,参数 encoding 也必须提供(参数 errors 可选),函数 bytearray() 返回的结果是字符串 source 对应编码 encoding 的字节数组。(通过调用函数 str.encode() 的方式转换);
  • 整数时(需大于等于0),则返回长度为这个整数(source)的空字节数组;
  • 实现了 buffer 接口的 object 对象时,那么将使用只读方式将字节读取到字节数组后返回;
  • 可迭代对象时,那么这个迭代对象的元素必须为 [0 ,255] 中的整数,以便可以初始化到数组里;
  • 缺省,则返回长度为 0 的字节数组。

示例

可选参数 source 为字符串时:

>>> bytearray('人生苦短')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
>>> bytearray('人生苦短', 'utf-8')
bytearray(b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad')
>>> bytearray('oooop')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
>>> bytearray('oooop', 'ascii')
bytearray(b'oooop')

可选参数 source 为整数或缺省时:

>>> bytearray(0)
bytearray(b'')
>>> bytearray(1)
bytearray(b'\x00')
>>> bytearray()
bytearray(b'')
>>> bytearray(-2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: negative count

可选参数 source 为可迭代对象时:

>>> bytearray([3, 4, 1])
bytearray(b'\x03\x04\x01')
>>> bytearray([3, 4, 256])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: byte must be in range(0, 256)
>>> bytearray([3, 4, 'a'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> bytearray((3, 4, 1))
bytearray(b'\x03\x04\x01')
>>> bytearray((3, 4, 'a'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required

修改 bytearray() 返回的数组元素:

>>> a=bytearray('好好学习,study', 'utf-8')
>>> a
bytearray(b'\xe5\xa5\xbd\xe5\xa5\xbd\xe5\xad\xa6\xe4\xb9\xa0\xef\xbc\x8cstudy')
>>> a=bytearray('好好学习,study', 'gbk')
>>> a
bytearray(b'\xba\xc3\xba\xc3\xd1\xa7\xcf\xb0\xa3\xacstudy')

>>> ii='人生苦短,我用Python!'
>>> bb=bytearray(ii, 'utf-8')
>>> bb
bytearray(b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python!')
>>> bb.decode()
'人生苦短,我用Python!'
>>> bb[:12]=bytearray('生命短暂', 'utf-8')
>>> bb
bytearray(b'\xe7\x94\x9f\xe5\x91\xbd\xe7\x9f\xad\xe6\x9a\x82\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python!')
>>> bb.decode()
'生命短暂,我用Python!'
>>>

bytes([source[, encoding[, errors]]])

返回一个新的字节数组(bytes)对象,数组里的元素是不可修改的,并且元素的取值范围为 [0, 255]。函数 bytes()bytearray() 的区别只是数组里的元素是否可以修改,而使用方法这些则是相同的,包括参数的定义方式及参数的意义也是相同的(参数定义说明请查看 bytearray() 函数)。

示例

>>> ii=bytes('abc', 'utf-8')
>>> ii
b'abc'
>>> ii[0]
97
>>> ii[1]
98
>>> ii[2]
99

>>> uu=bytes('中文汉字', 'utf-8')
>>> uu
b'\xe4\xb8\xad\xe6\x96\x87\xe6\xb1\x89\xe5\xad\x97'
>>> uu[0]
228
>>> uu[1]
184
>>> uu[2]
173

bytearraybytes 不一样的地方在于 bytearray 是可变的:

>>> ii='人生苦短,我用Python!'
>>> bb=bytearray(ii, 'utf-8')
>>> bb
bytearray(b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python!')
>>> bb.decode()
'人生苦短,我用Python!'
>>> bb[:12]=bytearray('生命短暂', 'utf-8')
>>> bb
bytearray(b'\xe7\x94\x9f\xe5\x91\xbd\xe7\x9f\xad\xe6\x9a\x82\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python!')
>>> bb.decode()
'生命短暂,我用Python!'
>>>

# 试图修改 bytes 返回的数组对象,提示错误:TypeError: 'bytes' object does not support item assignment
>>> ii
'人生苦短,我用Python!'
>>> uu=bytes(ii, 'utf-8')
>>> uu
b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python!'
>>> uu.decode()
'人生苦短,我用Python!'
>>> uu[:12]=bytes('生命短暂','utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment

callable(object)

该方法用来判断一个对象 object 是否可以被调用。

如果参数 object 是可被调用的,函数 callable() 返回 True,否则返回 False。不过,即使函数 callable() 返回 True,在实际调用中仍有可能会出现失败的情况,但如果返回的是 False,实际调用中肯定会失败。

说明:类对象都是可被调用对象(返回类的一个实例,如 ClassA());类的实例对象是否可调用对象,则取决于该类是否定义了 __call__() 方法。

示例

>>> class ClassA:
...     pass
...
>>> callable(ClassA)
True
>>> a=ClassA()
>>> callable(a)
False
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'ClassA' object is not callable

>>> class ClassB:
...     def __call__(self):
...             print('instances are callable')
...
>>> callable(ClassB)
True
>>> b=ClassB()
>>> callable(b)
True
>>> b()
instances are callable

chr(i)

返回整数 i 所对应的 Unicode 字符。如 chr(97) 返回字符串 achr(8364) 返回字符串 。它的功能与 ord() 函数相反。

说明:参数 i 为整数,取值范围必须在 0 - 1114111(十六进制为 0x10FFFF)之间,否则将报 ValueError 错误。

示例

>>> chr(8364)
'€'
>>> chr(97)
'a'
>>> chr('8364')  # 参数 *i* 必须为整数
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required (got type str)
>>> chr(-1)  # 取值范围必须在 [0, 1114111]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(0x110000)
>>> chr(1114112) # 取值范围必须在 [0, 1114111]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(0x110000)
>>> chr(0)
'\x00'
>>> chr(99)
'c'
>>> ord('c')  # 功能与 `ord()` 函数相反
99

classmethod(function)

该函数是一个装饰器函数,用来指定一个类的方法为类方法,没有此函数指定的类的方法则称为实例方法

声明类方法的语法如下:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

类方法的第一个参数是类对象参数,在方法被调用的时候自动将类对象传入,参数名称约定为 cls。如果一个方法被标示为类方法,则该方法可被类对象调用(如 C.f()),也可以被类的实例对象调用(如 C().f())。

另外,类被继承后,子类也可以调用父类的类方法,但是第一个参数传入的是子类的类对象。

示例

>>> class ClassA:
...     @classmethod
...     def class_method(cls, arg1):
...             print(cls)
...             print(arg1)
...
>>> ClassA.class_method('This is a class method.')
<class '__main__.ClassA'>
This is a class method.
>>> 
>>> ClassA().class_method('This is a class method.')
<class '__main__.ClassA'>
This is a class method.
>>> 
>>> 
>>> class ClassB(ClassA):
...     pass
...
>>> ClassB.class_method('Class method is called for a derived class.')
<class '__main__.ClassB'>
Class method is called for a derived class.
>>> 
>>> ClassB().class_method('Class method is called for a derived class.')
<class '__main__.ClassB'>
Class method is called for a derived class.

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

source 编译为代码或者AST对象,编译后的代码或对象可以被函数 exec()eval() 执行。

说明:

参数 source,可以是普通字符串、字节字符串或者是一个 AST(Abstract Syntax Trees) 对象。即需要动态执行的代码段。

参数 filename,代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了 source 参数时,filename 参数传入空字符即可。

参数 mode,指定编译代码的种类,代码的种类有三种,分别为 'exec'、'eval'、'single'。当 source 包含流程语句时,mode 应指定为 'exec';当 source 只包含单个表达式时,mode 应指定为 'eval';当 source 包含交互式命令语句,mode 则指定为 'single'。

示例

>>> cc = 'for i in range(0, 5): print(i)'
>>> com = compile(cc, '', 'exec')
>>> exec(com)
0
1
2
3
4
>>> cc = '2 + 3'
>>> com = compile(cc, '', 'eval')
>>> eval(com)
5
>>> cc = 'name = input("please input your name:")'
>>> com = compile(cc, '', 'single')
>>> exec(com)
please input your name:tim
>>> name
'tim'
>>> 

The filename argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file ('<string>'
is commonly used).

The mode argument specifies what kind of code must be compiled; it can be 'exec'
if source consists of a sequence of statements, 'eval'
if it consists of a single expression, or 'single'
if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than None
will be printed).

The optional arguments flags and dont_inherit control which future statements (see PEP 236) affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile()
.

If the flags argument is given and dont_inherit is not (or is zero) then the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it – the future statements in effect around the call to compile are ignored.

Future statements are specified by bits which can be bitwise ORed together to specify multiple statements. The bitfield required to specify a given feature can be found as the compiler_flag
attribute on the _Feature
instance in the future
module.
The argument optimize specifies the optimization level of the compiler; the default value of -1
selects the optimization level of the interpreter as given by -O
options. Explicit levels are 0
(no optimization; debug
is true), 1
(asserts are removed, debug
is false) or 2
(docstrings are removed too).
This function raises SyntaxError
if the compiled source is invalid, and ValueError
if the source contains null bytes.
If you want to parse Python code into its AST representation, see ast.parse()
.

Note
When compiling a string with multi-line code in 'single'
or 'eval'
mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the code
module.

class complex([real[, imag]])

返回一个值为 real + imag*j 的复数,或者把字符串或数字转化为复数。

说明:

当第一个参数 real 为 int 或者 float 类型时,第二个参数 imag 可以缺省,表示复数的虚部为 0 ;如果不缺省,则 imag 的类型也必须为 int 或者 float 。

当第一个参数 real 为字符串类型时,该字符串必须是一个能表示复数的字符串(如字符串 '1+2j''9-3j',注意:运算符 + 或者 - 左右不能出现空格,'1 + 2j' 是错误写法),且第二个参数 imag 必须缺省。

当第一个参数 real 和第二个参数 imag 都缺省时,该函数返回复数 0j。

示例

>>> complex(1, 2.3)
(1+2.3j)
>>> complex(6.8)
(6.8+0j)
>>> complex()
0j
>>> complex('1+2j')
(1+2j)
>>> complex('1 + 2j')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: complex() arg is a malformed string

delattr(object, name)

参数 object 是一个对象,参数 name 是一个字符串,函数的功能是删除对象 object 中名为 name 的属性。如 delattr(x,'foobar') 相当于删除对象 x 的 foobar 属性(即删除 x.foobar)。

示例

>>> class A:
...     def __init__(self, name):
...             self.name = name
...     def print_name(self):
...             print(self.name)
... 
>>> a = A('Tim')
>>> a.name
'Tim'
>>> delattr(a, 'age')  # 尝试删除一个不存在的属性 age
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: age
>>> 
>>> 
>>> delattr(a, 'name')  # 删除属性 name
>>> a.name  # 再次调用该属性时,提示“对象 x 不存在属性 name”错误
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'name'
>>> 

class dict(**kwarg)

class dict(mapping, **kwarg)

class dict(iterable, **kwarg)

字典类 dict 的构造函数。

示例

>>> dict()  # 不传入任何参数时,返回空字典
{}
>>> 
>>> 
>>> dict(code=200)  # 传入键值对创建字典
{'code': 200}
>>> 
>>> dict(code=200, msg='message')  # 传入键值对创建字典
{'code': 200, 'msg': 'message'}
>>> 
>>> dict(zip(['code','msg'], [200, 'message']))  # 传入映射函数创建字典
{'code': 200, 'msg': 'message'}
>>> 
>>> dict((('code', 200), ('msg', 'message')))  # 传入可迭代对象创建字典
{'code': 200, 'msg': 'message'}
>>> 

dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
If the object has a method named dir()
, this method will be called and must return the list of attributes. This allows objects that implement a custom getattr()
or getattribute()
function to customize the way dir()
reports their attributes.
If the object does not provide dir()
, the function tries its best to gather information from the object’s dict
attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom getattr()
.
The default dir()
mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:
If the object is a module object, the list contains the names of the module’s attributes.
If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

The resulting list is sorted alphabetically. For example:

import struct>>> dir() # show the names in the module namespace['builtins', 'name', 'struct']>>> dir(struct) # show the names in the struct module ['Struct', 'all', 'builtins', 'cached', 'doc', 'file', 'initializing', 'loader', 'name', 'package', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from']>>> class Shape:... def dir(self):... return ['area', 'perimeter', 'location']>>> s = Shape()>>> dir(s)['area', 'location', 'perimeter']

Note
Because dir()
is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

divmod(a, b)

该函数接收两个数字类型(非复数)参数,返回由这两个数值相除的商和余数组成的元组。

如果参数 a 与 参数 b 都是整数,函数返回的结果相当于 (a // b, a % b)

如果其中一个参数为浮点数时,函数返回的结果相当于 (q, a % b)q 通常是 math.floor(a / b),但也有可能是 1 ,比小,不过 q * b + a % b 的值会非常接近 a

如果 a % b 的求余结果不为 0 ,则余数的正负符号跟参数 b 是一样的,若 b 是正数,余数为正数,若 b 为负数,余数也为负数,并且 0 <= abs(a % b) < abs(b)

示例

>>> divmod(6, 5)
(1, 1)
>>> 6 // 5
1
>>> 6 % 5
1
>>> divmod(6, 3)
(2, 0)
>>> divmod(6, -2)
(-3, 0)
>>> divmod(6, -2.5)
(-3.0, -1.5)
>>> 
>>> divmod(6, 2.6)
(2.0, 0.7999999999999998)
>>> import math
>>> math.floor(6/2.6)
2
>>> 6%2.6
0.7999999999999998
>>> 
>>> divmod(6, 7)
(0, 6)
>>> 6 / 7
0.8571428571428571
>>> math.floor(6/7)
0
>>> 
>>> divmod(-6, 7)
(-1, 1)
>>> divmod(-6, -7)
(0, -6)
>>> -6/7
-0.8571428571428571
>>> math.floor(-6/7)
-1

enumerate(iterable, start=0)

该函数是把可迭代对象转换为枚举对象。

说明:
iterable 是必须是一个序列、迭代器或者其他支持迭代的对象,比如像列表、数组、字典等对象;
start 是枚举的起始值,默认是从0开始。

函数实现原理是这样,从迭代对象的方法 __next__() 取得一项值,然后就对参数 start 开始计数,每取一项增加 1,生成一个元组返回。该函数等价于:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

示例

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

eval(expression, globals=None, locals=None)

动态执行一个表达式的字符串,或者 compile() 函数编译出来的代码对象

说明:

参数 expression:必选,表达式字符串,或者 compile() 函数编译出来的代码对象;

参数 globals:可选(字典类型),全局命名空间,可以指定执行表达式时的全局作用域的范围,比如指定某些模块可以使用。如果本参数缺省,就使用当前调用这个函数的当前全局命名空间;

参数 locals:可选( mapping对象类型),局部作用域命名空间,是用来指定执行表达式时访问的局部命名空间。如果全局命名空间参数出现,但缺省内置模块,那么会自动拷贝这个模块到全局命名空间,意味着无论怎么设置,都可以使用内置模块。

如果参数 globals 和参数 locals 都使用缺省方式,就会使用调用这个函数时的命名空间来查找相应的变量。

示例

>>> x = 1
>>> eval('x+1')
2
>>>
>>>
>>> import math
>>> ALLOWED = {v: getattr(math, v)
... for v in filter(lambda x: not x.startswith('_'), dir(math))
... }
>>> print(eval('cos(90)', ALLOWED, {}))
-0.4480736161291701
>>>

exec(object[, globals[, locals]])

动态执行 Python 代码。

说明:

参数 object:一个字符串的语句或者一个 compile() 函数编译过的语句的对象名称。

参数 globals:全局命名空间,用来指定执行语句时可以访问的全局命名空间;

参数 locals:局部命名空间,用来指定执行语句时可以访问的局部作用域的命名空间。

要注意本函数不会返回任何值,不管函数或语句有任何的返回值语句,比 return
yield 语句。

如果参数 globalslocals 忽略,就会使用调用时所处的命名空间。这两个参数都要求是字典形式来说明命名空间。

示例

>>> exec('print(4+44)')
48

compileevalexec 函数的区别:

compile 函数是只编译字符串代码,而不作任何的执行,但它可以编译表达式或语句。

eval 函数是只执行表达式字符串代码,而不执行语句代码。

x = eval('%d + 6' % x)

exec 函数是只执行语句代码,而不执行表达式代码,因为它没有任何返回值。

filter(function, iterable)

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None
, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable)
is equivalent to the generator expression (item for item in iterable if function(item))
if function is not None
and (item for item in iterable if item)
if function is None
.

class float([x])

将数字或数字的字符串表示形式转换为与它等效的有符号浮点数。

说明:

如果参数 x 是一个字符串,则 x 应该是一个十进制数字的字符串表示形式,数字前面可以添加符号 +(表示正数)、-(表示负数),符号和数字之间不能出现空格,但是符号前面和数字后面允许出现空格。

>>> float('0xf')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '0xf'
>>> float('3.14159')
3.14159
>>> float('-3.14159')
-3.14159
>>> float('-     3.14159')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '-     3.14159'
>>> float('   -3.14159   ')
-3.14159
>>> float('   +3.14159   ')
3.14159

如果参数 x 是一个整数或是一个浮点数,则返回与它等效的浮点数;如果 x 超出了 float 类型的范围,则引发 OverflowError 错误。

>>> float(3)
3.0
>>> float(-3)
-3.0
>>> float(3.14159)
3.14159
>>> float(-3.14159)
-3.14159

如果参数 x 缺省,则返回 0.0

>>> float()
0.0

如果参数 x 是普通的Python对象,float([x]) 返回的是调用 x .__ float __() 结果。

示例

>>> class A:
...     def __init__(self, score):
...             self.score = score
...
>>> a = A(98)
>>> float(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: float() argument must be a string or a number, not 'A'
>>>

>>> class A:
...     def __init__(self, score):
...             self.score = score
...     def __float__(self):
...             return self.score
...
>>> a = A(98)
>>> float(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: A.__float__ returned non-float (type int)
>>> a = A(98.0)
>>> float(a)
98.0
>>>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容

  • //Clojure入门教程: Clojure – Functional Programming for the J...
    葡萄喃喃呓语阅读 3,604评论 0 7
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,495评论 18 139
  • 个人笔记,方便自己查阅使用 Py.LangSpec.Contents Refs Built-in Closure ...
    freenik阅读 67,666评论 0 5
  • 内置函数Python解释器内置了许多功能和类型,总是可用的。他们是按字母顺序列在这里。 abs(x)返回一个数的绝...
    uangianlap阅读 1,205评论 0 0
  • 好BOSS都有一个特质,喜欢琢磨。有的喜欢琢磨自个儿,有的喜欢琢磨别人。 哪里有可能被开发利用哪里就有TA忙碌的身...
    久十家乐阅读 260评论 0 0