id() 返回对象的唯一标识
内置函数 id(),Python 官方文档描述如下:
help(id)
Help on built-in function id in module builtins:
id(obj, /)
Return the identity of an object.
This is guaranteed to be unique among simultaneously existing objects.
(CPython uses the object's memory address.)
返回对象的唯一标识。该标识是一个整数,在此对象的生命周期中保证是唯一且恒定的。
CPython 中该标识是对象的内存地址。
id(1), id(1.0)
(140736642126656, 2785998726512)
1 == 1.0
True
# 两个变量引用了同一个值为 1 的对象
a = 1
b = int('01')
id(a), id(b)
(140736642126656, 140736642126656)
# 两个值为 1000 的不同对象
a = 1000
b = 1000
id(a), id(b)
(2785998745552, 2785998745360)
# 可变对象改变值,还是同一个对象
_list = [1,2,3]
print(id(_list),_list)
del _list[:]
print(id(_list),_list)
2785999307336 [1, 2, 3]
2785999307336 []
input() 接受输入返回字符串
内置函数 input(),Python 官方文档描述如下:
help(input)
Help on method raw_input in module ipykernel.kernelbase:
raw_input(prompt='') method of ipykernel.ipkernel.IPythonKernel instance
Forward raw_input to frontends
Raises
------
StdinNotImplentedError if active frontend doesn't support stdin.
如果存在 prompt 实参,则作为提示信息输出。接下来,该函数将输入转换为字符串并返回。无输入则返回空字符串。
input('输入提示:')
输入提示: 1+1
'1+1'
input('输入提示:')
输入提示:
''
int 创建整数
内置函数(类)int,Python 官方文档描述如下:
help(int)
Help on class int in module builtins:
class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10\. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
|
| Built-in subclasses:
| bool
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| self != 0
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Default object formatter.
|
| __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).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(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
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __round__(...)
| Rounding an Integral returns itself.
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(self, /)
| Returns size in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| __xor__(self, value, /)
| Return self^value.
|
| as_integer_ratio(self, /)
| Return integer ratio.
|
| Return a pair of integers, whose ratio is exactly equal to the original int
| and with a positive denominator.
|
| >>> (10).as_integer_ratio()
| (10, 1)
| >>> (-10).as_integer_ratio()
| (-10, 1)
| >>> (0).as_integer_ratio()
| (0, 1)
|
| bit_length(self, /)
| Number of bits necessary to represent self in binary.
|
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| to_bytes(self, /, length, byteorder, *, signed=False)
| Return an array of bytes representing an integer.
|
| length
| Length of bytes object to use. An OverflowError is raised if the
| integer is not representable with the given number of bytes.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value.
| signed
| Determines whether two's complement is used to represent the integer.
| If signed is False and a negative integer is given, an OverflowError
| is raised.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_bytes(bytes, byteorder, *, signed=False) from builtins.type
| Return the integer represented by the given array of bytes.
|
| bytes
| Holds the array of bytes to convert. The argument must either
| support the buffer protocol or be an iterable object producing bytes.
| Bytes and bytearray are examples of built-in objects that support the
| buffer protocol.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value.
| signed
| Indicates whether two's complement is used to represent the integer.
|
| ----------------------------------------------------------------------
| 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:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
将一个数字,字符串或字节串转换为整数。参数说明:
- 不给参数返回整数 0。
- 参数 x 为数字时,不能有参数 base,且数字不能是复数。浮点数将取整。
- 参数 x 为字符串或字节串,参数 base 可选,默认按十进制转换,否则按照 base 指定进制转换。
- base 取值范围为 0 和 2~36。
- base 取 0 将按照参数 x 的字面量来精确解释。取其他数字则需符合相应进制规则。
- 字符串或字节串不能是浮点数形式;前面可以有正负号;前后可以有空格,中间则不能有空格。
type(int)
type
int()
0
int(3.18e01), int(10), int(0x10)
(31, 10, 16)
int(' -10 '), int(b' +10')
(-10, 10)
int('10',2), int('10',8), int('z',36)
(2, 8, 35)
int('001'), int('0b10',0)
(1, 2)
int('001',0) # 001 不是合法的整数
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-12-1cf9048a8c3e> in <module>
----> 1 int('001',0)
ValueError: invalid literal for int() with base 0: '001'
int('9', 8) # 8 进制没有 9
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-13-3558097bd025> in <module>
----> 1 int('9', 8)
ValueError: invalid literal for int() with base 8: '9'
int('3.14') # 不能是浮点数形式
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-14-1456603af047> in <module>
----> 1 int('3.14')
ValueError: invalid literal for int() with base 10: '3.14'
isinstance() 是给定类的实例?
内置函数 isinstance(),Python 官方文档描述如下:
help(isinstance)
Help on built-in function isinstance in module builtins:
isinstance(obj, class_or_tuple, /)
Return whether an object is an instance of a class or of a subclass thereof.
A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
or ...`` etc.
如果对象 obj 是给定类的实例或者是其 (直接、间接或虚拟) 子类的实例则返回 True,不是则返回 False。给定的不是类则引发 TypeError 异常。
给定类可以以元组形式传参,obj 是其中任何一个类型的实例就返回 True。
isinstance(1, int)
True
isinstance('abc', (float, complex))
False
# bool 是 int 的子类型,但不是实例
isinstance(bool, int)
False
# True 是 int 的子类的实例
isinstance(True, int)
True
# bool 的实例只有 True 和 False
isinstance(1, bool)
False
# 所有的对象都是 object 的实例
isinstance(object, object)
True
import random # 模块
class A:pass # 自定义类
isinstance(1, object),\
isinstance(int, object),\
isinstance(list, object),\
isinstance(random, object),\
isinstance(A, object)
(True, True, True, True, True)
issubclass() 是给定类的子类吗?
内置函数 issubclass(),Python 官方文档描述如下:
help(issubclass)
Help on built-in function issubclass in module builtins:
issubclass(cls, class_or_tuple, /)
Return whether 'cls' is a derived from another class or is the same class.
A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
or ...`` etc.
如果类 cls 是给定类的 (直接、间接或虚拟) 子类则返回 True,不是则返回 False。给定的不是类则引发 TypeError 异常。
给定类可以以元组形式传参,cls 是其中任何一个类的子类就返回 True。
issubclass(1, int) # 1 不是类
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-257e7a8dbb04> in <module>
----> 1 issubclass(1, int)
TypeError: issubclass() arg 1 must be a class
issubclass(bool, int)
True
issubclass(bool, (set, str, list))
False
# 所有的类都是 object 的子类
class A:pass
issubclass(A, object),\
issubclass(str, object),\
issubclass(object, object)
(True, True, True)
iter() 转迭代器
内置函数 iter(),Python 官方文档描述如下:
help(iter)
Help on built-in function iter in module builtins:
iter(...)
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
将一个可迭代对象(iterable)或可调用对象(callable)转换为一个迭代器。
当参数是可调用对象时,需要提供参数 sentinel,生成的迭代器,每次
迭代时都会不带实参地调用 callable,返回 sentinel 时则触
发 StopIteration。
a = iter('abcd')
a
<str_iterator at 0x1c7eea4f910>
next(a),next(a),next(a),next(a)
('a', 'b', 'c', 'd')
a = iter(int, 1)
for i in range(3):
print(next(a))
0
0
0
a = iter(int, 0)
next(a)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-21-694e44f6d78c> in <module>
1 a = iter(int, 0)
----> 2 next(a)
StopIteration:
len() 返回元素个数
内置函数 len(),Python 官方文档描述如下:
help(len)
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
返回对象的长度(元素个数)。实参可以是序列(如 str、bytes、tuple、list 或 range 等的实例),集合(set 或 frozenset 的实例),或字典(dict 的实例)等。
len('123')
3
len('嗨')
1
len('嗨'.encode())
3
len([1,2,3])
3
len({'a':1,'b':2})
2
list 创建列表
内置函数(类)list,Python 官方文档描述如下:
help(list)
Help on class list in module builtins:
class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Implement self+=value.
|
| __imul__(self, value, /)
| Implement self*=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the list.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(self, /)
| Return the size of the list in memory, in bytes.
|
| append(self, object, /)
| Append object to the end of the list.
|
| clear(self, /)
| Remove all items from list.
|
| copy(self, /)
| Return a shallow copy of the list.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| extend(self, iterable, /)
| Extend list by appending elements from the iterable.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| insert(self, index, object, /)
| Insert object before index.
|
| pop(self, index=-1, /)
| Remove and return item at index (default last).
|
| Raises IndexError if list is empty or index is out of range.
|
| remove(self, value, /)
| Remove first occurrence of value.
|
| Raises ValueError if the value is not present.
|
| reverse(self, /)
| Reverse *IN PLACE*.
|
| sort(self, /, *, key=None, reverse=False)
| Stable sort *IN PLACE*.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
将一个可迭代对象转为列表。不传参数将得到空列表。
type(list)
type
list()
[]
list('123')
['1', '2', '3']
list({'a':1,'b':2})
['a', 'b']
locals() 返回局部变量的字典
内置函数 locals(),Python 官方文档描述如下:
help(locals)
Help on built-in function locals in module builtins:
locals()
Return a dictionary containing the current scope's local variables.
NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.
返回包含当前作用域的局部变量的字典。在模块层级上,locals() 和 globals() 是同一个字典。
globals() 和 locals() 函数各自返回当前的全局和本地字典,因此可以将它们传递给 eval() 或 exec() 来使用。
locals()
{'__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(locals)', 'locals()'],
'_oh': {},
'_dh': ['D:\\Jupyter\\xuecn_books\\books\\xue_python_kp\\11_built-in_function'],
'In': ['', 'help(locals)', 'locals()'],
'Out': {},
'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x0000023E24AE89B0>>,
'exit': <IPython.core.autocall.ZMQExitAutocall at 0x23e27368898>,
'quit': <IPython.core.autocall.ZMQExitAutocall at 0x23e27368898>,
'_': '',
'__': '',
'___': '',
'_i': 'help(locals)',
'_ii': '',
'_iii': '',
'_i1': 'help(locals)',
'_i2': 'locals()'}
def f():
a = 1
print(locals())
f()
{'a': 1}
map 以给定函数转换元素
内置函数(类)map,Python 官方文档描述如下:
help(map)
Help on class map in module builtins:
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
|
| 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.
返回一个将函数 func 应用于 iterable 中每一项并输出其结果的迭代器。
如果传入了额外的 iterable 参数,func 必须接受相同个数的实参并被应用于从所有可迭代对象中并行获取的项。
当有多个可迭代对象时,最短的可迭代对象耗尽则整个迭代就将结束。
type(map)
type
a = map(int, '1234')
a
<map at 0x16048be3828>
list(a)
[1, 2, 3, 4]
m = map(int,'abc',(16,16))
list(m)
[10, 11]
def f(x,y):
d = {}
d[x] = y
return d
m = map(f,'abc',(1,2))
list(m)
[{'a': 1}, {'b': 2}]
max() 求最大项
内置函数 max(),Python 官方文档描述如下:
help(max)
Help on built-in function max in module builtins:
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
返回可迭代对象中最大的元素,或多个实参中最大的项。参数说明:
- 如果只提供了一个位置参数,它必须是可迭代对象(iterable),返回 iterable 中最大的元素,iterable 为空,返回 default。
- 如果提供了两个及以上的位置参数,则返回最大的位置参数。
- 如果有多个最大元素,则此函数将返回第一个找到的。
- 参数 key(可选)指定排序函数,将排序的项都经此函数计算,按计算值取最大的项。
max('3142')
'4'
max([], default=0)
0
max(2,4,3,4)
4
max([2,1],[2,1,1])
[2, 1, 1]
max(('a','ab','bcd'),key=len)
'bcd'
min() 求最小项
内置函数 min(),Python 官方文档描述如下:
help(min)
Help on built-in function min in module builtins:
min(...)
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.
返回可迭代对象中最小的元素,或多个实参中最小的项。参数说明:
- 如果只提供了一个位置参数,它必须是可迭代对象(iterable),返回 iterable 中最小的元素,iterable 为空,返回 default。
- 如果提供了两个及以上的位置参数,则返回最小的位置参数。
- 如果有多个最小元素,则此函数将返回第一个找到的。
- 参数 key(可选)指定排序函数,将排序的项都经此函数计算,按计算值取最小的项。
min('3142')
'1'
min([], default=0)
0
min(2,3,2,4)
2
min([2,1],[2,1,1])
[2, 1]
min(('a','ab','bcd'),key=len)
'a'
next() 返回迭代器下一个元素
内置函数 next(),Python 官方文档描述如下:
help(next)
Help on built-in function next in module builtins:
next(...)
next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.
返回迭代器(iterator)的下一个元素。如果迭代器耗尽,则返回给定的 default,如果没有默认值则触发 StopIteration。
i = iter('123')
next(i,'迭代结束')
'1'
next(i,'迭代结束')
'2'
next(i,'迭代结束')
'3'
next(i,'迭代结束')
'迭代结束'
next(i,'迭代结束')
'迭代结束'