enumerate 枚举
内置函数(类)enumerate,Python 官方文档描述如下:
help(enumerate)
Help on class enumerate in module builtins:
class enumerate(object)
| enumerate(iterable, start=0)
|
| Return an enumerate object.
|
| iterable
| an object supporting iteration
|
| The enumerate object yields pairs containing a count (from start, which
| defaults to zero) and a value yielded by the iterable argument.
|
| enumerate is useful for obtaining an indexed list:
| (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
返回一个可迭代对象(iterable)的枚举对象。枚举对象是一个迭代器,迭代出来是一个个元组,里面包含一个计数值(从 start 开始,默认为 0)和通过迭代 iterable 获得的值。
type(enumerate)
type
e = enumerate({'a':1,'b':2,'c':3})
e
<enumerate at 0x200ccb71240>
next(e)
(0, 'a')
for i in e:
print(i)
(1, 'b')
(2, 'c')
e = enumerate('abc', 1)
list(e)
[(1, 'a'), (2, 'b'), (3, 'c')]
eval() 解析字符串或代码并求值
内置函数 eval(),Python 官方文档描述如下:
help(eval)
Help on built-in function eval in module builtins:
eval(source, globals=None, locals=None, /)
Evaluate the given source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
source 参数接受字符串(会作为一个 Python 表达式)或代码对象(可通过 compile() 创建),然后解析并求值,返回求值结果。
eval('{1 + 1}')
{2}
s = 'for i in range(3):print(i)'
code = compile(s,'','exec')
eval(code)
0
1
2
eval("__import__('math').sqrt(3**2+4**2)")
5.0
参数 globals 和 locals 作为 source 的全局和局部命名空间。如果省略 locals 字典则其默认值为 globals 字典。如果两个字典同时省略,则表达式执行时会使用 eval() 被调用的环境中的全局和局部名称。
如果 globals 字典存在且不包含以 __builtins__
为键的值,则会在解析 source 之前插入以此为键的对内置模块 builtins 的引用。这意味着 source 通常具有对标准 builtins 模块的完全访问权限且受限的环境会被传播。
globals 实参必须是一个字典。locals 可以是任何映射对象。
x = 3
def f():
y = 4
code = "__import__('math').sqrt(x**2+y**2)"
z = eval(code,{'x':5},{'y':12})
print(f'x={x}, y={y}, z={z}')
f()
x=3, y=4, z=13.0
x = 3
def f():
y = 4
code = "__import__('math').sqrt(x**2+y**2)"
z = eval(code,{'x':5,'y':12})
print(f'x={x}, y={y}, z={z}')
f()
x=3, y=4, z=13.0
x = 3
def f():
y = 4
code = "__import__('math').sqrt(x**2+y**2)"
z = eval(code)
print(f'x={x}, y={y}, z={z}')
f()
x=3, y=4, z=5.0
exec() 解析字符串或代码并求值
内置函数 exec(),Python 官方文档描述如下:
help(exec)
Help on built-in function exec in module builtins:
exec(source, globals=None, locals=None, /)
Execute the given source in the context of globals and locals.
The source may be a string representing one or more Python statements
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
这个函数支持动态执行 Python 代码。source 必须是字符串或者代码对象。
如果是字符串,那么该字符串将被解析为一系列 Python 语句并执行(除非发生语法错误)。
如果是代码对象,它将被直接执行。
该函数返回值为 None。
print(exec('{1 + 1}'))
None
s = 'for i in range(3):print(i)'
code = compile(s,'','exec')
exec(code)
0
1
2
参数 globals 和 locals 作为 source 的全局和局部命名空间。如果省略 locals 字典则其默认值为 globals 字典。如果两个字典同时省略,则表达式执行时会使用 eval() 被调用的环境中的全局和局部名称。
如果 globals 字典存在且不包含以 __builtins__
为键的值,则将为该键插入对内建 builtins 模块字典的引用。因此,在将执行的代码传递给 exec() 之前,可以通过将自己的 __builtins__
字典插入到 globals 中来控制可以使用哪些内置代码。
globals 实参必须是一个字典。locals 可以是任何映射对象。
x = 1
def f():
x = 2
code = "for i in range(x):print(i)"
exec(code,{'x':3},{'x':4})
f()
0
1
2
3
x = 1
def f():
x = 2
code = "for i in range(x):print(i)"
exec(code,{'x':3})
f()
0
1
2
x = 1
def f():
x = 2
code = "for i in range(x):print(i)"
exec(code)
f()
0
1
filter 真值元素筛选
内置函数(类)filter,Python 官方文档描述如下:
help(filter)
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
返回可迭代对象(iterable)中那些传递给函数 function 计算之后,布尔值仍然为真的元素组成的迭代器。
如果 function 是 None,则会假设它是一个身份函数,即 iterable
中所有布尔值为假的元素会被移除。
type(filter)
type
f = filter(None,[0,1,2,1])
list(f)
[1, 2, 1]
f = filter(lambda x: x-1, [0,1,2,1])
list(f)
[0, 2]
list(filter(None,'0120'))
['0', '1', '2', '0']
list(filter(int,'0120'))
['1', '2']
float 创建浮点数
内置函数(类)float,Python 官方文档描述如下:
help(float)
Help on class float in module builtins:
class float(object)
| float(x=0, /)
|
| Convert a string or number to a floating point number, if possible.
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| self != 0
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Formats the float according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __round__(self, ndigits=None, /)
| Return the Integral closest to x, rounding half toward even.
|
| When an argument is passed, work like built-in round(x, ndigits).
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(self, /)
| Return the Integral closest to x between 0 and x.
|
| as_integer_ratio(self, /)
| Return integer ratio.
|
| Return a pair of integers, whose ratio is exactly equal to the original float
| and with a positive denominator.
|
| Raise OverflowError on infinities and a ValueError on NaNs.
|
| >>> (10.0).as_integer_ratio()
| (10, 1)
| >>> (0.0).as_integer_ratio()
| (0, 1)
| >>> (-.25).as_integer_ratio()
| (-1, 4)
|
| conjugate(self, /)
| Return self, the complex conjugate of any float.
|
| hex(self, /)
| Return a hexadecimal representation of a floating-point number.
|
| >>> (-0.1).hex()
| '-0x1.999999999999ap-4'
| >>> 3.14159.hex()
| '0x1.921f9f01b866ep+1'
|
| is_integer(self, /)
| Return True if the float is an integer.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __getformat__(typestr, /) from builtins.type
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
|
| It exists mainly to be used in Python's test suite.
|
| This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
| little-endian' best describes the format of floating point numbers used by the
| C type named by typestr.
|
| __set_format__(typestr, fmt, /) from builtins.type
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
| fmt
| Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian',
| and in addition can only be one of the latter two if it appears to
| match the underlying C reality.
|
| It exists mainly to be used in Python's test suite.
|
| Override the automatic determination of C-level floating point type.
| This affects how floats are converted to and from binary strings.
|
| fromhex(string, /) from builtins.type
| Create a floating-point number from a hexadecimal string.
|
| >>> float.fromhex('0x1.ffffp10')
| 2047.984375
| >>> float.fromhex('-0x1p-1074')
| -5e-324
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| imag
| the imaginary part of a complex number
|
| real
| the real part of a complex number
返回从数字或字符串 x 生成的浮点数。
如果实参是字符串:
- 它必须是包含十进制数字的字符串;
- 通常是 Python 整数或浮点数的字符串形式;
- 也可以是 ‘NaN’(非数字)、表示正负无穷大的字符串(“Infinity” 或 “inf”)。字母大小写随意;
- 字符串前后可以有空白字符。
如果实参是整数或浮点数,则返回具有相同值(在 Python 浮点精度范围内)的浮点数。如果实参在 Python 浮点精度范围外,则会触发OverflowError。
如果没有实参,则返回 0.0 。
type(float)
type
float()
0.0
float(1)
1.0
float(- 1.0)
-1.0
float(' -1.0 \n')
-1.0
float(' 01_2.1_4 ')
12.14
float('0001')
1.0
float('3.14e02')
314.0
float('-naN')
nan
float('-inf')
-inf
format() 格式化
内置函数 format(),Python 官方文档描述如下:
help(format)
Help on built-in function format in module builtins:
format(value, format_spec='', /)
Return value.__format__(format_spec)
format_spec defaults to the empty string.
See the Format Specification Mini-Language section of help('FORMATTING') for
details.
将 value 转换为 format_spec 控制的 “格式化” 表示。format_spec 的解释取决于 value 实参的类型,但是大多数内置类型使用标准格式化语法:格式化迷你语言。详见 str.format 格式化。
默认的 format_spec 是一个空字符串,它通常和调用 str(value) 的结果相同。
format('嗨','>10')
' 嗨'
format('嗨','~^10')
'~~~~嗨~~~~~'
format(1,'05')
'00001'
format(3.14,'.3f')
'3.140'
format(123456789,'_')
'123_456_789'
format(123456789,'.2e')
'1.23e+08'
format(123456789)
'123456789'
frozenset 创建不可变集合
内置函数(类)frozenset,Python 官方文档描述如下:
help(frozenset)
Help on class frozenset in module builtins:
class frozenset(object)
| frozenset() -> empty frozenset object
| frozenset(iterable) -> frozenset object
|
| Build an immutable unordered collection of unique elements.
|
| Methods defined here:
|
| __and__(self, value, /)
| Return self&value.
|
| __contains__(...)
| x.__contains__(y) <==> y in x.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __rand__(self, value, /)
| Return value&self.
|
| __reduce__(...)
| Return state information for pickling.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(...)
| S.__sizeof__() -> size of S in memory, in bytes
|
| __sub__(self, value, /)
| Return self-value.
|
| __xor__(self, value, /)
| Return self^value.
|
| copy(...)
| Return a shallow copy of a set.
|
| difference(...)
| Return the difference of two or more sets as a new set.
|
| (i.e. all elements that are in this set but not the others.)
|
| intersection(...)
| Return the intersection of two sets as a new set.
|
| (i.e. all elements that are in both sets.)
|
| isdisjoint(...)
| Return True if two sets have a null intersection.
|
| issubset(...)
| Report whether another set contains this set.
|
| issuperset(...)
| Report whether this set contains another set.
|
| symmetric_difference(...)
| Return the symmetric difference of two sets as a new set.
|
| (i.e. all elements that are in exactly one of the sets.)
|
| union(...)
| Return the union of sets as a new set.
|
| (i.e. all elements that are in either set.)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
将可迭代对象转换为集合,返回一个新的 frozenset 集合对象。可迭代对象为空,或不传参数,得到一个空集合。
type(frozenset)
type
frozenset()
frozenset()
frozenset([])
frozenset()
frozenset('0123')
frozenset({'0', '1', '2', '3'})
frozenset({'a':1,'b':2})
frozenset({'a', 'b'})
getattr() 获取对象的属性
内置函数 getattr(),Python 官方文档描述如下:
help(getattr)
Help on built-in function getattr in module builtins:
getattr(...)
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
返回对象给定的属性名指向的值。name 必须是字符串。如果该字符串是对象的属性名称之一,则返回该属性的值。例如,getattr(x, 'y')
等同于 x.y
。如果指定的属性不存在,且提供了 default 值,则返回它,否则触发 AttributeError。
getattr(1,'imag')
0
getattr(1,'bool',True)
True
getattr(1,'bool')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-524bb2b35e58> in <module>
----> 1 getattr(1,'bool')
AttributeError: 'int' object has no attribute 'bool'
class A:
y = 1
x = A()
x.y
1
getattr(x,'y')
1
globals() 返回全局变量字典
内置函数 globals(),Python 官方文档描述如下:
help(globals)
Help on built-in function globals in module builtins:
globals()
Return the dictionary containing the current scope's global variables.
NOTE: Updates to this dictionary *will* affect name lookups in the current
global scope and vice-versa.
返回包含当前作用域的全局变量字典。这总是当前模块的字典(在函数或方法中,不是调用它的模块,而是定义它的模块)。
更新此字典 将 影响当前全局范围内的名称查找,反之亦然。
globals() 和 locals() 函数各自返回当前的全局和本地字典,因此可以将它们传递给 eval() 或 exec() 来使用。
globals()
{'__name__': '__main__',
'__doc__': 'Automatically created module for IPython interactive environment',
'__package__': None,
'__loader__': None,
'__spec__': None,
'__builtin__': <module 'builtins' (built-in)>,
'__builtins__': <module 'builtins' (built-in)>,
'_ih': ['', 'help(globals)', 'globals()'],
'_oh': {},
'_dh': ['D:\\Jupyter\\xuecn_books\\books\\xue_python_kp\\11_built-in_function'],
'In': ['', 'help(globals)', 'globals()'],
'Out': {},
'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x000001E15E70D748>>,
'exit': <IPython.core.autocall.ZMQExitAutocall at 0x1e160f63978>,
'quit': <IPython.core.autocall.ZMQExitAutocall at 0x1e160f63978>,
'_': '',
'__': '',
'___': '',
'_i': 'help(globals)',
'_ii': '',
'_iii': '',
'_i1': 'help(globals)',
'_i2': 'globals()'}
hasattr() 是对象的属性吗?
内置函数 hasattr(),Python 官方文档描述如下:
help(hasattr)
Help on built-in function hasattr in module builtins:
hasattr(obj, name, /)
Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError.
该函数实参是一个对象和一个字符串。如果字符串是对象的属性之一的名称,则返回 True,否则返回 False。
hasattr('abc', 'join')
True
class A:
y = 1
hasattr(A, 'y')
True
hash() 返回对象的哈希值
内置函数 hash(),Python 官方文档描述如下:
help(hash)
Help on built-in function hash in module builtins:
hash(obj, /)
Return the hash value for the given object.
Two objects that compare equal must also have the same hash value, but the
reverse is not necessarily true.
返回对象的哈希值(如果它有的话)。哈希值是整数。它们在集合或字典查找元素时用来快速比较集合的元素或字典的键。相同大小的数字有相同的哈希值。
可哈希对象必须具有相同的哈希值比较结果才会相同。
hash(1) == hash(1.0) == hash(True)
True
1 == 1.0 == True
True
hash('abc')
2812132477407752679
hash((1,2,3))
529344067295497451
hash([1,2,3])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-35e31e935e9e> in <module>
----> 1 hash([1,2,3])
TypeError: unhashable type: 'list'
hash((1,2))
help 启动帮助系统
内置函数(帮助系统)help,Python 官方文档描述如下:
help(help)
Help on _Helper in module _sitebuiltins object:
class _Helper(builtins.object)
| Define the builtin 'help'.
|
| This is a wrapper around pydoc.help that provides a helpful message
| when 'help' is typed at the Python interactive prompt.
|
| Calling help() at the Python prompt starts an interactive help session.
| Calling help(thing) prints help for the python object 'thing'.
|
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
启动内置的帮助系统(此函数主要在交互式中使用)。
如果没有实参,解释器控制台里会启动交互式帮助系统。
如果实参是一个字符串,则在模块、函数、类、方法、关键字或文档主题中搜索该字符串,并在控制台上打印帮助信息。
如果实参是其他任意对象,则会生成该对象的帮助页。
type(help)
_sitebuiltins._Helper
help()
Welcome to Python 3.8's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.8/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
help> print
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
help> q
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
help('list.append')
Help on method_descriptor in list:
list.append = append(self, object, /)
Append object to the end of the list.
help(list.append)
Help on method_descriptor:
append(self, object, /)
Append object to the end of the list.
hex() 整数的十六进制形式
内置函数 hex(),Python 官方文档描述如下:
help(hex)
Help on built-in function hex in module builtins:
hex(number, /)
Return the hexadecimal representation of an integer.
>>> hex(12648430)
'0xc0ffee'
将整数转换为以 0x
为前缀的小写十六进制整数的字符串形式。
hex(123)
'0x7b'
0x7b
123