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
>>>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • //Clojure入門教程: Clojure – Functional Programming for the J...
    葡萄喃喃囈語閱讀 3,766評論 0 7
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,923評論 18 139
  • 個人筆記,方便自己查閱使用 Py.LangSpec.Contents Refs Built-in Closure ...
    freenik閱讀 67,768評論 0 5
  • 內置函數Python解釋器內置了許多功能和類型,總是可用的。他們是按字母順序列在這里。 abs(x)返回一個數的絕...
    uangianlap閱讀 1,263評論 0 0
  • 好BOSS都有一個特質,喜歡琢磨。有的喜歡琢磨自個兒,有的喜歡琢磨別人。 哪里有可能被開發利用哪里就有TA忙碌的身...
    久十家樂閱讀 295評論 0 0