分多次讲解
这部分相对比较简单,偶尔一些特殊的做法会强调下(前面加★)
builtins = [_ for _ in dir(__builtins__) if not _[0].isupper() and _[0] != '_']
print('一共有{}个内置对象'.format(len(builtins))) # 73
print(builtins)
['abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
类别 | 函数|类 | 作用 |
---|---|---|
数学 | abs | 求绝对值 |
divmod | 求商和余数 | |
max | 最大 | |
min | 最小 | |
pow | 求幂 | |
round | 保留几位小数 | |
sum | 求和 | |
进制 | bin | 二进制 |
hex | 十六进制 | |
oct | 八进制 | |
类型 | bool | 求布尔 |
bytes | 转换成字节类型 | |
complex | 复数 | |
dict | 转换为dict | |
float | 转换为float | |
frozenset | 冻结集合 | |
int | 转换为int | |
list | 转换为list | |
set | 转换为set | |
str | 转换为str | |
tuple | 转换为tuple | |
迭代器 | iter | 迭代 |
enumerate | 枚举 | |
next | 下一个 | |
range | 范围 | |
reversed | 逆向迭代器 | |
转换 | chr | 转换得到字符unicode |
classmethod | 转换为类方法 | |
staticmethod | 转换为静态方法 | |
ord | 跟chr的反操作 | |
对象 | callable | 检查一个对象是否是可调用的 |
delattr | 删除属性 | |
getattr | 获取属性 | |
setattr | 设置属性 | |
dir | 查看对象属性方法 | |
isinstance | 是否是对象实例 | |
issubclass | 是否为子类 | |
super | 父类 | |
type | 查看对象类型 | |
vars | 返回对象信息 | |
函数式编程 | filter | 过滤 |
map | 映射 | |
sorted | 排序 | |
输入输出 | 输出 | |
input | 输入 | |
其他 | all | 都为真才为真 |
any | 一个为真就为真 | |
ascii | ascii转换 | |
format | 格式化 | |
id | 返回对象标识 | |
len | 求容器长度 | |
help | 获取帮助 | |
globals | 当前的全局变量 | |
hash | 返回该对象的哈希值 | |
eval | 计算 | |
exec | 执行 | |
repr | 返回对象的str格式 | |
open | 打开文件 | |
property | 属性 | |
zip | 压缩 | |
冷门 | exit | 退出 |
locals | 以字典类型返回当前位置的全部局部变量 | |
memoryview | 返回给定参数的内存查看对象 | |
object | 无属性的根类 | |
breakpoint | 调试相关,断点 | |
bytearray | 字节数组 | |
compile | 编译成代码或 AST 对象 | |
copyright | ??? | |
credits | ??? | |
license | ??? | |
quit | 退出 | |
slice | 切片 |
abs(x, /)
Return the absolute value of the argument.
abs(-1) # 1
>>> abs(x=-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: abs() takes no keyword arguments
divmod(x, y, /)
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
b = 7
c = 3
div,mod = divmod(b,c)
print('商是',div,f'也就是{b}//{c}',)
print('余数是',mod,f'也就是{b}%{c}')
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.
max(1,2) # 2
max(1,2,3) # 3
max([1,2,3,4]) # 4 # 本质上,这3种都是iterable,前2个传递的是元组,也可以是列表等容器
names = 'wuxianfeng','qianhanyi','qianyuli'
max(names) # 得到的是wuxianfeng,首字符的ascii,如果一样依次比较下去
names = 'wuxianfeng','qianhanyi','qianyuli','helloworld!!!'
max(names,key=len) # 这个key就是排序的依据 # 得到的是长度最长的
nums = [123,45,6789,-12345]
max(nums,key=abs) # 求离原点最远的数
nums = [[10,2],[20,3],[40,5],[30,4]]
max(nums,key=lambda x:x[1]) # [40,5] # 如果是一个坐标x,y,那就是y坐标最大的数
min(nums,key=lambda x:x[1]) # [10,2] # min就不讲了,跟max是一样的
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.
pow(base, exp, mod=None)
Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
pow(2,3) # 2的3次方 8
pow(2,3,3) # 8 % 3 余2 ==>2
pow(2,3,4) # 8 % 4 没有余数 ==> 0
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
round(3.1415,2) # 3.14
round(3.1415,3) # 3.142
round(999993.1415,-3) # 1000_000.0
round(999793.1415,-2) # 999800.0
sum(iterable, /, start=0)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
sum(1,2,3)
TypeError Traceback (most recent call last)
<ipython-input-35-dd9496db4b54> in <module>
----> 1 sum(1,2,3)
TypeError: sum() takes at most 2 arguments (3 given)
sum([1,2,3]) # 6
sum((1,2,3)) # 6
sum([1,2,3],start=2) # 8 = 6+2
这部分没有高级用法,也非常简单,看example就行了
bin(number, /)
Return the binary representation of an integer.
>>> bin(2796202)
'0b1010101010101010101010'
type(bin(10)) # str
oct(number, /)
Return the octal representation of an integer.
>>> oct(342391)
'0o1234567'
hex(number, /)
Return the hexadecimal representation of an integer.
>>> hex(12648430)
'0xc0ffee'
这个分类下的都跟类型有关系
class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
|
| Method resolution order:
| bool
| int
| object
|
| Methods defined here:
|
| __and__(self, value, /)
| Return self&value.
|
| __or__(self, value, /)
| Return self|value.
|....(还有很多魔术方法)
bool(1) # True
bool(0) # False
bool('a') #True
bool([]) # False # 写到这里你会发现就是if 条件后面的东西
bool([0,0,0]) # True
issubclass(bool,int) # True
class bytes(object)
| bytes(iterable_of_ints) -> bytes
| bytes(string, encoding[, errors]) -> bytes
| bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
| bytes(int) -> bytes object of size given by the parameter initialized with null bytes
| bytes() -> empty bytes object
|
| Construct an immutable array of bytes from:
| - an iterable yielding integers in range(256)
| - a text string encoded using the specified encoding
| - any object implementing the buffer API.
| - an integer
这是一个相对复杂的类
bytes() 返回一个空的bytes对象
bytes(数字) 这个数字就是大小(长度),每个初始化为\x00
bytes(5) # b'\x00\x00\x00\x00\x00'
bytes(bytes_or_buffer),这个不知道咋用(没用过)
bytes(iterable_of_ints)
bytes([1,2,3,4]) # b'\x01\x02\x03\x04'
用的最多的是这种,bytes里面塞一个str,并指定encoding,作用是将字符串转换为字节序列
# 一定要给出encoding参数
bytes('hello')
TypeError Traceback (most recent call last)
<ipython-input-16-34da9840e7ee> in <module>
----> 1 bytes('hello')
TypeError: string argument without an encoding
bytes('hello','utf-8') # b'hello'
bytes('中国','gbk') #b'\xd6\xd0\xb9\xfa'
bytes('中国','utf-8') # b'\xe4\xb8\xad\xe5\x9b\xbd'
class complex(object)
| complex(real=0, imag=0)
|
| Create a complex number from a real part and an optional imaginary part.
|
| This is equivalent to (real + imag*1j) where imag defaults to 0.
|
| Methods defined here:
|
a = 1+3j
type(a) #complex
complex(2,3) # 2+3j
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
dict这个内置方法的用法是很多同学一开始的时候会忽略的
dict() 返回一个空字典,类型的这些内置函数(类)多数支持这个方法
dict(mapping)
dict(zip(['a','b'],(1,2))) # {'a': 1, 'b': 2} # 这里要用到一个zip的做法,zip是非常值得深入学习的一个内置函数
dict(iterable)
dict([('a',1),('b',2)]) # {'a': 1, 'b': 2}
dict(**kwargs)
dict(a=1,b=2) # {'a': 1, 'b': 2}
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)
这个用起来比较简单
float('2') # 2.0
float(1) # 1.0
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.
冻结的集合,不可修改,看这个的方法,跟普通的set的区别
fz = frozenset([1,1,3,2,3]) # {1,2,3}
[_ for _ in dir(fz) if _[0]!='_']
# ['copy','difference','intersection','isdisjoint','issubset','issuperset','symmetric_difference','union']
[_ for _ in dir(set) if _[0]!='_']
# ['add','clear','copy','difference','difference_update','discard','intersection','intersection_update','isdisjoint','issubset','issuperset','pop','remove','symmetric_difference','symmetric_difference_update','union','update']
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
|
这个类是在做进制转换的时候非常有用
int('10') # 得到 10
int('10',2) # 得到2 , 10在二进制中就是2
int('11',2) # 3
int('ff',16) # 255
int('FF',16) # 255 不会区分大小写
int('12',3) # 3进制中12表示5 , 还可以这些乱七八糟的进制表示
int('0b100',base=0) # 如果是base是0,就自己从前面的str中解析得到是个什么进制的数
int('0b100',0)
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.
这个你可能是用的非常多的,没啥好说的
list() # 空的list
list(1,2,3) # 别这样,错了
list({1,2,3})
list((1,2,3))
list(range(5)) # 可迭代的即可
class set(object)
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
set()得到一个空集合
set(可迭代对象)可以得到一个新的集合对象
set([1,2,3,1,2]) # {1,2,3}
set() # {} 空的set
set({'a':1,'b':2}) # {'a','b'}
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
可以返回对象的repr或者__str__
class P:
def __repr__(self):
return 'ppppp'
p1 = P()
print(str(p1)) # 你不加str也是一样的
最简单的用法
str(1) # '1'
str({'a':1}) # "{'a': 1}"
class tuple(object)
| tuple(iterable=(), /)
|
| Built-in immutable sequence.
|
| If no argument is given, the constructor returns an empty tuple.
| If iterable is specified the tuple is initialized from iterable's items.
|
| If the argument is a tuple, the return value is the same object.
|
| Built-in subclasses:
| asyncgen_hooks
| UnraisableHookArgs