1.abs(x):返回数字的绝对值,x可以是整数、浮点数、复数;
注:若x是复数,则返回其大小
import math
a = -1
b = -1.3232
c = b
d = 1+1.0j
e = 3+4.0j
f="a"
g=[1,2]
print ("a的绝对值是:",abs(a)) # 1
print("b的绝对值是:",abs(b)) # 1.3232
print("c的绝对值是:",math.fabs(c)) # 1.3232
print("d的的绝对值是:",abs(d)) # 1.4142135623730951
# print("e的绝对值是:",math.fabs(e)) # 报错:TypeError: can't convert complex to float
# print("f的的绝对值是:",abs(f)) # 报错:TypeError: bad operand type for abs(): 'str'
# print("g的的绝对值是:",abs(g)) # 报错:TypeError: bad operand type for abs(): 'list'
2.all(iterable):(1)iterable非空的前提下,并且iterable里的元素全为true,则返回True,否则返回False;(2)iterable为空,则返回True
print(all(["a",[2,3],1,True])) # True
print(all(["a",[],1,True])) # False
print(all(["a",[2,3],0,True])) # False
print(all(["a",[2,3],10,False])) # False
print(all(("a",[2,3],1,True))) # True
print(all(("a",[],1,True))) # False
print(all(("a",[2,3],0,True))) # False
print(all(("a",[2,3],10,False))) # False
print(all("dsajf")) # True
# print(all(12345)) # 报错:TypeError: 'int' object is not iterable
print(all([1,2,3])) # True
print(all([])) # True
print(all(())) # True
print(all({})) # True
print(all("")) # True
3.any(iterable):(1)iterable非空的前提下,并且iterable里的元素只要有1个为true,则返回True,否则返回False;(2)iterable为空,则返回False
print(any(["a",[2,3],1,True])) # True
print(any(["a",[],1,True])) # True
print(any(["a",[2,3],0,True])) # True
print(any(["a",[2,3],10,False])) # True
print(any(("a",[2,3],1,True))) # True
print(any(("a",[],1,True))) # True
print(any(("a",[2,3],0,True))) # True
print(any(("a",[2,3],10,False))) # True
print(any("dsajf")) # True
# print(all(12345)) # 报错:TypeError: 'int' object is not iterable
print(any([1,2,3])) # True
print(any([])) # False
print(any(())) # False
print(any({})) # False
print(any("")) # False
4.ascii(obj):返回一个对象可打印的字符串,与repr(obj)略有区别, repr() 返回的字符串中非 ASCII 编码的字符,会使用 \x、\u 和 \U 来转义,而ascii()不会
print(ascii(1)) # 1
print(ascii("1")) # '1'
print(ascii("a")) # 'a'
print(ascii([1,2,3])) # [1, 2, 3]
print(ascii((2,3,4))) # (2, 3, 4)
print(ascii("点击")) # '\u70b9\u51fb'
print(repr(1)) # 1
print(repr("1")) # '1'
print(repr("a")) # 'a'
print(repr([1,2,3])) # [1, 2, 3]
print(repr((2,3,4))) # (2, 3, 4)
print(repr("点击")) # '点击'
5.bin(x):将一个整数转变为一个前缀为“0b”的二进制字符串
print(bin(1)) # 0b1
# print(bin(1.1)) # 报错:TypeError: 'float' object cannot be interpreted as an integer
print(bin(0)) # 0b0
# print(bin(0.0)) # 报错:TypeError: 'float' object cannot be interpreted as an integer
print(bin(-2)) # -0b10
# print(bin("a")) # 报错:TypeError: 'str' object cannot be interpreted as an integer
6.bool(x):返回一个布尔值,True 或者 False。如果 x 是假的或者被省略,返回 False;其他情况返回 True。bool 类是 int 的子类,其他类不能继承自它,它只有 False 和 True 两个实例。在 3.7 版中,x 现在只能作为位置参数。
print(bool(0)) # False
print(bool(0.0)) # False
print(bool(1)) # True
print(bool(1.1)) # True
print(bool()) # False
print(bool(())) # False
print(bool([])) # False
print(bool(None)) # False
print(bool(1.1)) # True
print(bool(True)) # True
print(bool(False)) # False
print(bool(0+0j)) # False
print(bool(set())) # False
print(bool(range(0))) # False
print(bool("a")) # True
print(bool) # <class 'bool'>
print(True) # True
print(True+1) # 2
print(False) # False
print(False+1) # 1
7.breakpoint(*args, **kws):运行到此函数时,会陷入到调试器中。实际调用的是 sys.breakpointhook() ,直接传递 args 和 kws 。默认情况下, sys.breakpointhook() 调用 pdb.set_trace() 且没有参数。
def test_ic(favourite_ic):
user_guess = input("Try to guess our favourite IC >>> ")
breakpoint()
if user_guess == favourite_ic:
return "Yup, that's our favourite!"
else:
return "Sorry, that's not our favourite IC"
if __name__ == '__main__':
favourite_ic = 555
print(test_ic(favourite_ic))
运行截图:


8.bytearray([source[, encoding[, errors]]]):返回一个新的 bytes 数组。 bytearray 类是一个可变序列,包含范围为 0 <= x < 256 的整数。它有可变序列大部分常见的方法,见 可变序列类型 的描述;同时有 bytes 类型的大部分方法,参见 bytes 和 bytearray 操作。
# 如果是一个整数,将会按照整数的数值,使用对应数量的空字节(\x00)来表示。比如参数为5,那么返回的结果则是b'\x00\x00\x00\x00\x00';必须为非负数,否则报错;
b=bytearray(2)
print(b) # bytearray(b'\x00\x00')
print(len(b)) # 2
b=bytearray(0)
print(b) # bytearray(b'')
print(len(b)) # 0
# b=bytearray(-2) # 报错:ValueError: negative count
# 如果是一个字符串,还必须给出编码,否则会报错
# 当source参数为实现了buffer接口的object对象时,那么将使用只读方式将字节读取到字节数组后返回
b=bytearray("abc","utf-8")
print(b) # bytearray(b'abc')
print(len(b)) # 3
# b=bytearray("abc") # 报错:TypeError: string argument without an encoding
# 如果是一个 iterable 可迭代对象(列表(list),元组(tuple),range()方法以及for循环),它的元素的范围必须是 0 <= x < 256 的整数,它会被用作数组的初始内容
b=bytearray([1,2])
print(b) # bytearray(b'\x01\x02')
print(len(b)) # 2
b=bytearray((1,2))
print(b) # bytearray(b'\x01\x02')
print(len(b)) # 2
b=bytearray(set((1,2)))
print(b) # bytearray(b'\x01\x02')
print(len(b)) # 2
b=bytearray(range(1,2))
print(b) # bytearray(b'\x01')
print(len(b)) # 1
b=bytearray(i for i in range(1,5))
print(b) # bytearray(b'\x01\x02\x03\x04')
print(len(b)) # 4
# 如果没有参数,则创建一个大小为0的数组。
b=bytearray()
print(b) # bytearray(b'')
print(len(b)) # 0
以下是常见方法:
(1)clear():该方法无返回值
b=bytearray(i for i in range(1,5))
print(b.clear()) # None
print(b) # bytearray(b'')
b=bytearray()
b.clear()
print(b) # bytearray(b'')
print(len(b)) # 0
(2)append(x):0≤x<256,x为整数,该方法无返回值
b=bytearray(i for i in range(1,5))
print(b.append(7)) # None
print(b) # bytearray(b'\x01\x02\x03\x04\x07')
b=bytearray()
b.append(1)
print(b) # bytearray(b'\x01')
print(len(b)) # 1
b.append(0)
print(b) # bytearray(b'\x01\x00')
b.append(255)
print(b) # bytearray(b'\x01\x00\xff')
# b.append(-1) #报错:ValueError: byte must be in range(0, 256)
# b.append((2,3)) # 报错:TypeError: an integer is required
9.bytes([source[, encoding[, errors]]]):返回一个新的 bytes 数组。 bytearray 类是一个不可变序列,包含范围为 0 <= x < 256 的整数。
b=bytes(2)
print(b) # b'\x00\x00'
print(len(b)) # 2
b=bytes("abc","utf-8")
print(b) # b'abc'
print(len(b)) # 3
# b=bytes("abc") # 报错:TypeError: string argument without an encoding
b=bytes("啦","utf-8")
print(b) # b'\xe5\x95\xa6'
print(len(b)) # 3
b=bytes("你好","utf-8")
print(b) # b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(len(b)) # 6
b=bytes(2)
print(b) # b'\x00\x00'
print(len(b)) # 2
b=bytes("abc","utf-8")
print(b) # b'abc'
print(len(b)) # 3
b=bytes([1,2])
print(b) # b'\x01\x02'
print(len(b)) # 2
b=bytes((1,2))
print(b) # bb'\x01\x02'
print(len(b)) # 2
b=bytes(set((1,2)))
print(b) # b'\x01\x02'
print(len(b)) # 2
b=bytes(range(1,2))
print(b) # b'\x01'
print(len(b)) # 1
b=bytes()
print(b) # b''
print(len(b)) # 0
# b=bytes(range(1,257)) #报错: ValueError: bytes must be in range(0, 256)
10.callable(obj):检测obj是否可调用
(1)对于函数、方法、lambda 函式、 类、实现了 __call__ 方法的类实例, 都是可调用
(2)对于整数,字符串,列表,元组,字典等不可调用
print(callable(0)) # False
print(callable(1)) # False
print(callable("abc")) # False
print(callable([1,2])) # False
print(callable((2,3))) # False
print(callable(set([1,2]))) # False
def add(a,b):
return a+b
print(callable(add)) # True
class A:
"""docstring for A"""
def abc(self):
return 0
print(callable(A)) # True
a=A()
print(callable(a)) # False
class B:
def __call__(self):
return 0
print(callable(B)) # True
b=B()
print(callable(b)) # True
f=lambda x: x+1
print(callable(f)) # True
11.chr(i):返回 Unicode 码位为整数 i 的字符的字符串格式
(1)实参的合法范围是 0 到 1,114,111(16 进制表示是 0x10FFFF)。如果 i 超过这个范围,会触发 ValueError 异常
print(chr(97)) # a
print(chr(90)) # Z
print(chr(0)) #
print(chr(8364)) # €
print(chr(125)) # }
print(chr(0x30)) # 0
# print(chr(12345678)) # 报错:ValueError: chr() arg not in range(0x110000)
12.@classmethod:把一个方法封装成类方法
(1)3种类定义方法:常规方法、@classmethod修饰方法、@staticmethod修饰方法
class A():
def foo(self, x):
print("1-executing foo(%s,%s)" % (self, x))
print('1-self:', self)
@classmethod
def class_foo(cls, x):
print("2-executing class_foo(%s,%s)" % (cls, x))
print('2-cls:', cls)
@staticmethod
def static_foo(x):
print("3-executing static_foo(%s)" % x)
a = A()
1)普通的类方法foo()需要通过self参数隐式的传递当前类对象的实例; @classmethod修饰的方法class_foo()需要通过cls参数传递当前类对象;@staticmethod修饰的方法定义与普通函数一样。self和cls的区别不是强制的,只是PEP8中一种编程风格,self通常用作实例方法的第一参数,cls通常用作类方法的第一参数。即通常用self来传递当前类对象的实例,cls传递当前类对象
2)foo方法绑定对象A的实例,class_foo方法绑定对象A,static_foo没有参数绑定
print(a.foo) # <bound method A.foo of <__main__.A object at 0x0000028D5A300BA8>>
print(a.class_foo) # <bound method A.class_foo of <class '__main__.A'>>
print(a.static_foo) # <function A.static_foo at 0x0000028D5AAD2840>
3)foo可通过实例a调用,类对像A直接调用会参数错误
print(a.foo(1)) # 1-executing foo(<__main__.A object at 0x0000017229EC0BA8>,1)
# 1-self: <__main__.A object at 0x0000017229EC0BA8>
# None
# print(A.foo(1)) # 报错:TypeError: foo() missing 1 required positional argument: 'x'
4)但foo如下方式可以使用正常,显式的传递实例参数a
print(A.foo(a,1)) # 1-executing foo(<__main__.A object at 0x000002608CDD0BA8>,1)
# 1-self: <__main__.A object at 0x000002608CDD0BA8>
# None
5)class_foo通过类对象或对象实例调用
print(A.class_foo(1)) # 2-executing class_foo(<class '__main__.A'>,1)
# 2-cls: <class '__main__.A'>
# None
print(a.class_foo(1)) # 2-executing class_foo(<class '__main__.A'>,1)
# 2-cls: <class '__main__.A'>
# None
6)static_foo通过类对象或对象实例调用
print(A.static_foo(1)) # 3-executing static_foo(1)
# None
print(a.static_foo(1)) # 3-executing static_foo(1)
# None
7)继承与覆盖普通类函数是一样的
class B(A):
pass
b = B()
b.foo(1) # 1-executing foo(<__main__.B object at 0x0000018E5FF10FD0>,1)
# 1-self: <__main__.B object at 0x0000018E5FF10FD0>
b.class_foo(1) # 2-executing class_foo(<class '__main__.B'>,1)
# 2-cls: <class '__main__.B'>
b.static_foo(1) # 3-executing static_foo(1)
8)@staticmethod是把函数嵌入到类中的一种方式,函数就属于类,同时表明函数不需要访问这个类。通过子类的继承覆盖,能更好的组织代码
9)区别:@staticmethod 会硬编码,就是说,方法中返回的类名必须与当前的 class 名称一致
@classmethod 是软编码,该方法传递的第一个参数使 cls ,cls 默认绑定了当前的类名
具体例子可见:https://blog.csdn.net/grace666/article/details/100990469
class Fuck:
sex = '每日' #这就是非绑定的属性
@staticmethod
def sta():
return Fuck.sex
@classmethod
def cla(cls):
return cls.sex #@classmethod里面必须要传入一个参数,这个参数代表就是当前的类
class Fuck_everybody(Fuck): #因为Fuck_everybody继承了父类Fuck,所以Fuck_everybody可以调用父类的sta()方法与cla()方法
pass
print(Fuck_everybody.sta()) # 每日
print(Fuck_everybody.cla()) # 每日
# 然后我突然不爽,把Fuck删掉了
del Fuck
#那么,你再试试
# print(Fuck_everybody.sta()) # 报错:NameError: name 'Fuck' is not defined
print(Fuck_everybody.cla()) # 每日
#虽然删掉,但是仍能执行
https://www.zhihu.com/question/20021164?sort=created
13.compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1):
(1)source:常规的字符串、字节字符串,或者 AST (抽象语法树)对象
filename:实参需要是代码读取的文件名;如果代码不需要从文件中读取,可以传入一些可辨识的值(经常会使用 '<string>')
mode:指定编译代码必须用的模式。如果 source 是语句序列,可以是 'exec';如果是单一表达式,可以是 'eval';如果是单个交互式语句,可以是 'single'。(在最后一种情况下,如果表达式执行结果不是 None 将会被打印出来。)
flags:变量作用域,局部命名空间,如果被提供,可以是任何映射对象
flags和dont_inherit是用来控制编译源码时的标志,如果两者都未提供(或都为零)则会使用调用 compile() 的代码中有效的 future 语句来编译代码。 如果给出了 flags 参数但没有 dont_inherit (或是为零) 则 flags 参数所指定的 以及那些无论如何都有效的 future 语句会被使用。 如果 dont_inherit 为一个非零整数,则只使用 flags 参数 -- 在调用外围有效的 future 语句将被忽略
optimize:实参指定编译器的优化级别;默认值 -1 选择与解释器的 -O 选项相同的优化级别;显式级别为 0 (没有优化;__debug__ 为真)、1 (断言被删除, __debug__ 为假)或 2 (文档字符串也被删除)
如果编译的源码不合法,此函数会触发 SyntaxError 异常;如果源码包含 null 字节,则会触发 ValueError 异常
14.complex([real[, imag]]) 复数
real---int、float、long、字符串
imag---int、float、long
当real为int、float、long时,imag可缺省或同样为int、float、long
当real为字符串时,则imag必须为能表示复数的字符串形式,如“1+2j”、“1-3j”,但是中间的“+”或“-”号两边不能有空格,并且imag必须缺省
当real和imag都缺省,返回0j
print(complex()) # 0j
print(complex(1, 2)) # (1+2j)
print(complex(3)) # (3+0j)
print(complex("4")) # (4+0j)
print(complex(5 + 3j)) # (5+3j)
print(complex("6+5j")) # (6+5j)
print(complex("6-5j")) # (6-5j)
print(complex("6.1+5.2j")) # (6.1+5.2j)
print(complex("6.1")) # (6.1+0j)
print(complex("1+2j")) # (1+2j)
print(complex(" 1+2j")) # (1+2j)
print(complex(" 1+2j ")) # (1+2j)
# print(complex("1 +2j")) # 报错:ValueError: complex() arg is a malformed string
可以使用下划线将代码文字中的数字进行分组:
print(complex("2_3")) # (23+0j)
print(complex("1_1")) # (11+0j)
print(complex("0_10")) # (10+0j)
print(complex("1_0")) # (10+0j)
print(complex("0_0")) # 0j
print(complex("1_2_3")) # (123+0j)
print(complex("1_2_3_4")) # (1234+0j)
print(complex("1_2+3j")) # (12+3j)
print(complex("0_2+3j")) # (2+3j)
15.dir():
(1)如果没有实参,则返回当前本地作用域中的名称列表
print(dir()) # ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'ctime', 'datetime', 'pymongo', 'reduce']
(2)如果有实参,它会尝试返回该对象的有效属性列表
print(dir([])) # ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
def x():
return 1
print(dir(x)) # ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
class A():
pass
print(dir(A)) # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
s=A()
print(dir(s)) # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
(3)如果对象有一个名为 __dir__() 的方法,那么该方法将被调用,并且必须返回一个属性列表
class A():
def __dir__(self):
return "yyy"
print(dir(A)) # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
s=A()
print(dir(s)) # ['y', 'y', 'y']
16.divmod(a, b):它将两个(非复数)数字作为实参,并在执行整数除法时返回一对商和余数
(1)若a和b都为整数,函数返回的结果相当于 (a // b, a % b)
a=100
b=20
print(divmod(a,b)) # (5, 0)
a=100
b=30
print(divmod(a,b)) # (3, 10)
a=0
b=5
print(divmod(a,b)) # (0, 0)
(2)若a和b中有1个浮点数,函数返回的结果相当于 (q, a % b),q 通常是 math.floor(a / b),但也有可能是 1 ,比小,不过 q * b + a % b 的值会非常接近 a
a=100.25
b=20
print(divmod(a,b)) # (5.0, 0.25)
a=100.25
b=21.1
print(divmod(a,b)) # (4.0, 15.849999999999994)
(3)如果 a % b 的求余结果不为 0 ,则余数的正负符号跟参数 b 是一样的,若 b 是正数,余数为正数,若 b 为负数,余数也为负数,并且 0 <= abs(a % b) < abs(b)
a=-8
b=5
print(divmod(a,b)) # (-2, 2)
a=8
b=-5
print(divmod(a,b)) # (-2, -2)
a=-8
b=-5
print(divmod(a,b)) # (1, -3)
(4)除数不能为0,或者a/b不能为复数
# a=100
# b=0
# print(divmod(a,b)) # 报错:ZeroDivisionError: integer division or modulo by zero
# a=100+5j
# b=20
# print(divmod(a,b)) # 报错:TypeError: can't take floor or mod of complex number.
17.enumerate(iterable, start=0):用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中,默认下标从0开始,也可自定义
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(enumerate(seasons)) # <enumerate object at 0x00000226EEC4ABD0>
print(list(enumerate(seasons))) # [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
print(tuple(enumerate(seasons))) # ((0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter'))
print(set(enumerate(seasons))) # {(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')}
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons))) # [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
print(list(enumerate(seasons,1))) # [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
18.delattr(object, name):删除对象object的属性name,object是对象,name是字符串,name必须是object的某个属性。如果对象允许,该函数将删除指定的属性
class A:
x=1
y=-2
z=3
def aa(self):
print("hello")
a=A()
print("x = ",a.x) # x = 1
print("y = ",a.y) # y = -2
print("z = ",a.z) # z = 3
a.aa() # hello
delattr(A, 'z')
print("x = ",a.x) # x = 1
print("y = ",a.y) # y = -2
# print("z = ",a.z) # 报错:AttributeError: 'A' object has no attribute 'z'
# delattr(A, 't') # 报错:AttributeError: t
delattr(A, 'aa')
# a.aa() # 报错:AttributeError: 'A' object has no attribute 'aa'
delattr(x, 'foobar') 等价于 del x.foobar
class A:
x=1
y=-2
z=3
def aa(self):
print("hello")
a=A()
print("x = ",a.x) # x = 1
print("y = ",a.y) # y = -2
print("z = ",a.z) # z = 3
a.aa() # hello
del A.z
print("x = ",a.x) # x = 1
print("y = ",a.y) # y = -2
# print("z = ",a.z) # 报错:AttributeError: 'A' object has no attribute 'z'
del A.aa
# a.aa() # 报错:AttributeError: 'A' object has no attribute 'aa'
19.eval(expression[, globals[, locals]]):可参考 https://mp.csdn.net/postedit/90639536
20.exec(object[, globals[, locals]]):可参考 https://blog.csdn.net/grace666/article/details/101294711
21.filter(function, iterable):用来过滤序列中不符合条件的元素,返回的是迭代器对象,用的话需要进行转换,比如要转换为列表,可以使用 list() 来转换;接收两个参数,第一个function为函数,第二个iterable为序列,iterable的每个元素作为参数传递给function进行判,然后返回 True 或 False,最后将返回 True 的元素放到新的迭代器中;
注, filter(function, iterable) 相当于一个生成器表达式,当 function 不是 None 的时候为 (item for item in iterable if function(item));function 是 None 的时候为 (item for item in iterable if item)
def is_odd(n):
return n%2==1
alist=[1,2,3,4,5,6]
temp=filter(is_odd, alist)
print(temp) # <filter object at 0x000001DCE49A0AC8>
newlist=list(temp)
print(newlist) # [1, 3, 5]
newtuple=tuple(temp)
print(newtuple) # ()
temp=filter(is_odd, alist)
newtuple=tuple(temp)
print(newtuple) # (1, 3, 5)
alist=[1,2,3,4,5,6]
temp=filter(None, alist)
print(temp) # <filter object at 0x0000019DF5D10A90>
newlist=list(temp)
print(newlist) # [1, 2, 3, 4, 5, 6]
alist=[1,2,3,0,5,6,0,False,"a","","ee"," ","b",(),"c",[],"d",{},"f",set(),"g",range(0)]
temp=filter(None, alist)
print(temp) # <filter object at 0x0000018BD3060AC8>
newlist=list(temp)
print(newlist) # [1, 2, 3, 5, 6, 'a', 'ee', ' ', 'b', 'c', 'd', 'f', 'g']
ps:python2中该函数返回的是list,而Python3中改成迭代器,这样的好处为了节省内存,因为map和filter等函数返回一个迭代器,这个迭代器具有类生成器的特性,是懒加载的,它只有在下次调用的时候才会去计算本次生成的值,而不是像列表那样预先生成所有的值然后每次调用返回列表中的下一个值。这种方式需要将所有的值预先保存在列表中,当列表很大的时候这是非常消耗内存的
22.float([x]):返回从数字或字符串 x 生成的浮点数,可参考 https://blog.csdn.net/grace666/article/details/90639536
23.format(value[, format_spec]):将 value 转换为 format_spec 控制的“格式化”表示
(1)format_spec的格式: [[fill]align][sign][#][0][width][grouping_option][.precision][type]
(2)format_spec默认为空字符串,等同于 str(value)
(3)fill:可为任意字符,fill是可选的,但是如果设置了fill,就必须和align搭配使用
align:对齐方式
| 选项 | 含义 |
| '<' | 强制字段在可用空间内左对齐(这是大多数对象的默认值) |
| '>' | 强制字段在可用空间内右对齐(这是数字的默认值) |
| '=' | 强制将填充放置在符号(如果有)之后但在数字之前,此对齐选项仅对数字类型有效,否则报错 |
| '^' | 强制字段在可用空间内居中 |
print(format(2918))
print(format(0x500, 'X'))
print(format(3.14, '0=10'))
print(format(3.14159, '05.3'))
print(format(3.14159, 'E'))
print(format('test', '<20'))
print(format('test', '>20'))
print(format('test', '^20'))
#打印值:
# 2918
# 500
# 0000003.14
# 03.14
# 3.141590E+00
# test
# test
# test
左对齐:
#字符“test”左对齐
print(format('test', '<')) # test
print(format('test', '@<')) # test
#字符“test”左对齐,宽度为5,不足以“@”补齐
print(format('test', '@<5')) # test@
#字符“test”左对齐,宽度为4,不足以“@”补齐
print(format('test', '@<4')) # test
#字符“test”左对齐,宽度为3,不足以“@”补齐
print(format('test', '@<3')) # test
#给出fill,就必须要和align搭配使用,否则报错
# print(format('test', '@')) # 报错:ValueError: Unknown format code '@' for object of type 'str'
#字符“test”左对齐,宽度为10,不足以“@”补齐
print(format('test', '@<10')) # test@@@@@@
右对齐:
#字符“test”右对齐
print(format('test', '>')) # test
print(format('test', '$>')) # test
#字符“test”右对齐,宽度为5
print(format('test', '$>5')) # $test
#字符“test”右对齐,宽度为4,不足以“$”补齐
print(format('test', '$>4')) # test
#字符“test”右对齐,宽度为3,不足以“$”补齐
print(format('test', '$>3')) # test
#字符“test”右对齐,宽度为10,不足以“$”补齐
print(format('test', '$>10')) # $$$$$$test
居中:
#字符“test”空间内居中
# print(format('test', '*')) # 报错:ValueError: Unknown format code '*' for object of type 'str'
print(format('test', '*^')) # test
#字符“test”空间内居中,宽度为5
print(format('test', '*^5')) # test*
#字符“test”空间内居中,宽度为4,不足以“$”补齐
print(format('test', '*^4')) # test
#字符“test”空间内居中,宽度为3,不足以“$”补齐
print(format('test', '*^3')) # test
#字符“test”空间内居中,宽度为10,不足以“$”补齐
print(format('test', '*^10')) # ***test***
填充数字宽度
# 非数字类型
# print(format('test', '@=10')) # 报错:ValueError: '=' alignment not allowed in string format specifier
print(format(123, '=')) # 123
#数字“123”宽度为5,不足以“@”补足
print(format(123, '@=5')) # @@123
#数字“123”宽度为4,不足以“@”补齐
print(format(123, '@=4')) # @123
#数字“123”宽度为3,不足以“@”补齐
print(format(123, '@=3')) # 123
#数字“123”宽度为10,不足以“@”补齐
print(format(123, '@=10')) # @@@@@@@123
# print(format(12.13, '=')) # 12.13
# #数字“12.13”宽度为6,不足以“@”补足
# print(format(12.13, '@=6')) # @12.13
# #数字“12.13”宽度为5,不足以“@”补齐
# print(format(12.13, '@=5')) # 12.13
# #数字“12.13”宽度为4,不足以“@”补齐
# print(format(12.13, '@=4')) # 12.13
# #数字“12.13”宽度为10,不足以“@”补齐
# print(format(12.13, '@=10')) # @@@@@12.13
(4)sign:符号,仅对数字有效
| 选项 | 含义 |
| '+' | 表示标志应该用于正数和负数 |
| '-' | 表示标志应仅用于负数(这是默认行为) |
| space | 表示应在正数上使用前导空格,在负数上使用减号 |
print(format(123, '+')) #+123
print(format(123, '-')) #123
print(format(-123, '+')) #-123
print(format(-123, '-')) #-123
print(format(123, '>5')) # 123
print(format(123, ' >5')) # 123
print(format(123, '>+5')) # +123
print(format(123, '>-5')) # 123
print(format(-123, '>+5')) # -123
print(format(-123, '>-5')) # -123
print(format(123, ' ')) # 123
print(format(-123, ' ')) #-123
# print(format(123, ' ')) #2个空格报错:ValueError: Unknown format code '\x20' for object of type 'int'
print(format(1.23, ' ')) # 1.23
print(format(-1.23, ' ')) #-1.23
(5)#:数字的格式,仅对整数、浮点、复数和 Decimal 类型有效;对于整数类型,当使用二进制、八进制或十六进制输出时,此选项会为输出值添加相应的 '0b', '0o' 或 '0x' 前缀; 对于浮点数、复数和 Decimal 类型,替代形式会使得转换结果总是包含小数点符号,即使其不带小数;通常只有在带有小数的情况下,此类转换的结果中才会出现小数点符号; 此外,对于 'g' 和 'G' 转换,末尾的零不会从结果中被移除
print(format(123, '#')) #123
print(format(-123, '#')) #-123
print(format(0x500, '#')) #1280
print(hex(1280)) #0x500
#二进制/八进制/十六进制数
print(format(123, '#b')) #0b1111011
print(format(123, '#o')) #0o173
print(format(123, '#x')) #0x7b
print(format(123, 'b')) #1111011
print(format(123, 'o')) #173
print(format(123, 'x')) #7b
#带g或G的数
print(format(123, '#g')) #123.000
print(format(123, '#G')) #123.000
print(format(123.000, '#')) #123.0
print(format(123, 'g')) #123
print(format(123, 'G')) #123
print(format(123.000, '')) #123.0
#小数
print(format(1.235, '#')) #1.235
print(format(11.0, '#')) #11.0
print(format(12., '#')) #12.0
print(format(1.235, '')) #1.235
print(format(11.0, '')) #11.0
print(format(12., '')) #12.0
print(format(float(12), '#')) #12.0
print(format(float(12), '')) #12.0
#复数
print(format(2+3j, '#')) #(2.+3.j)
print(format(2+3j, '')) #(2.+3j)
(6)0:针对数字的对齐,当没有明确给出对齐方式时,则在width选项前面加'0'字符可以为数字类型是字符0进行填充。这相当于填充字符'0',对齐类型为'='
print(format(123, '0=')) #123
print(format(0x500, '0=10')) #0000001280
print(format(1.23, '0=')) #1.23
print(format(1.23, '0=10')) #0000001.23
(7)width:最小字段宽度的十进制整数, 如果未指定,则字段宽度将由内容确定
print(format(123, '10')) # 123
print(format("abc", '10')) #abc
# print(format("abc", '010')) #报错:ValueError: '=' alignment not allowed in string format specifier
print(format("abcdefg", '10')) #abcdefg
# print(format([1,2,3], '10')) #报错:TypeError: unsupported format string passed to
当未显式给出对齐方式时,在 width 字段前加一个零 ('0') 字段将为数字类型启用感知正负号的零填充, 这相当于设置 fill 字符为 '0' 且 alignment 类型为 '='
print(format(123, '10')) # 123
print(format(123, '010')) #0000000123
(8)grouping_option:千位分隔符
| 选项 | 含义 |
| ',' | 选项表示使用逗号(,)作为千位分隔符。 对于感应区域设置的分隔符,请改用 'n' 整数表示类型 |
| '_' | 表示对浮点表示类型和整数表示类型 'd' 使用下划线(_)作为千位分隔符。 对于整数表示类型 'b', 'o', 'x' 和 'X',将为每 4 个数位插入一个下划线。 对于其他表示类型指定此选项则将导致错误 |
print(format(123, ',')) #123
print(format(12.3, ',')) #12.3
print(format(123456789, ',')) #123,456,789
print(format(1.23456789, ',')) #1.23456789
print(format(123, '_')) #123
print(format(12.3, '_')) #12.3
print(format(123456789, '_')) #123_456_789
print(format(1.23456789, '_')) #1.23456789
(9).precision:
对于数字类型,如以 'f' and 'F' 格式化的浮点数值要在小数点后显示多少位,或者对于以 'g' 或 'G' 格式化的浮点数值要在小数点前后共显示多少个数位, 对于整数值则不允许使用 precision
# print(format(123, ".5")) #报错:ValueError: Precision not allowed in integer format specifier
print(format(12.3, ".5")) # 12.3
print(format(1.23456789, '.5')) #1.2346
对于非数字类型,该字段表示最大字段大小 —— 换句话说就是要使用多少个来自字段内容的字符
print(format("adsffsd", '.5')) #adsff
(10)type:数据类型
针对字符串:
| 类型 | 含义 |
| 's' | 字符串格式。这是字符串的默认类型,可以省略 |
| None(不设置) | 和 's' 一样 |
print(format("abc", "s")) #abc
print(format("abc", )) #abc
print(format("abc","" )) #abc
# print(format(12.3, "s")) #报错:ValueError: Unknown format code 's' for object of type 'float'
# print(format(123, 's')) #报错:ValueError: Unknown format code 's' for object of type 'int'
针对整数:
| 类型 | 含义 |
| 'b' | 二进制格式, 输出以 2 为基数的数字 |
| 'c' | 字符,在打印之前将整数转换为相应的unicode字符 |
| 'd' | 十进制整数, 输出以 10 为基数的数字 |
| 'o' | 八进制格式, 输出以 8 为基数的数字 |
| 'x' | 十六进制格式, 输出以 16 为基数的数字,使用小写字母表示 9 以上的数码 |
| 'X' | 十六进制格式, 输出以 16 为基数的数字,使用大写字母表示 9 以上的数码 |
| 'n' | 数字, 这与 'd' 相似,不同之处在于它会使用当前区域设置来插入适当的数字分隔字符,在中文语言环境是没有分隔符的。可以使用locale模块进行切换 |
| None | 和 'd' 相同 |
print(format(123, "b")) #1111011
print(format(123, "c")) #{
print(format(123, "d")) #123
print(format(123, "o")) #173
print(format(123, "x")) #7b
print(format(123, "X")) #7B
print(format(123, "n")) #123
print(format(123, "")) #123
print(format(123, )) #123
针对浮点和小数:
| 类型 | 含义 |
| 'e' | 指数表示, 以使用字母 'e' 来标示指数的科学计数法打印数字, 默认的精度为 6 |
| 'E' | 指数表示, 与 'e' 相似,不同之处在于它使用大写字母 'E' 作为分隔字符。、 |
| 'f' | 定点表示, 将数字显示为一个定点数, 默认的精确度为 6;如果原数字小数点后位数超过6位且第7位大于5,则第6位+1,但第7位等于5时,则要看是否存在第8位且大于0,如大于0,第6位也+1,如果原数字小数点后不足6位的,则以0补充。如果指定了精度则按上述规则推算即可 |
| 'F' | 定点表示。 与 'f' 相似,但会将 nan 转为 NAN 并将 inf 转为 INF。 |
| 'g' | 常规格式。 对于给定的精度 p >= 1,这会将数值舍入到 p 位有效数字,再将结果以定点格式或科学计数法进行格式化,具体取决于其值的大小。 一般格式,在未设置精度的情况下,它保留6位数(整数+小数),根据实际情况选择以固定位数或者科学计数法格式化结果,结果后面如果存在多余的0将会被舍去。有以及几种规则:如果整数位已经等于精度,则舍掉所有小数,并且以小数的第一位四舍五入进整数;如果整数位大于精度,则以exp指数的形式格式化,以精度位的下一位作为判断依据四舍五入;如果整数位不足精度位数,则使用小数位补充,不存在小数位或者整数位+小数位不足精度,则显示完整数字;如果整数位不足精度位数,且小数位大于剩余精度,则截取小数位剩余精度,以后一位小数为判断是否舍去还是进一,如后一位小数大于5,则进一,如后一小数小于5,则舍去,如后一位小数等于5且后二位小数大于0,则进一。
精度 0 会被视为等同于精度 1。 默认精度为 6。 |
| 'G' | 常规格式。 类似于 'g',不同之处在于当数值非常大时会切换为 'E'。 无穷与 NaN 也会表示为大写形式。 |
| 'n' | 数字, 这与 'g' 相似,不同之处在于它会使用当前区域设置来插入适当的数字分隔字符,在中文语言环境是没有分隔符的。可以使用locale模块进行切换。 |
| '%' | 百分比。 将数字乘以 100 并显示为定点 ('f') 格式,后面带一个% |
| None | 类似于 'g',不同之处在于当使用定点表示法时,小数点后将至少显示一位, 默认精度与表示给定值所需的精度一样, 整体效果为与其他格式修饰符所调整的 str() 输出保持一致 |
“e”和“E”
print(format(12.3, "e")) #1.230000e+01
print(format(12.3, "E")) #1.230000E+01
print(format(12.3456789, "e")) #1.234568e+01
print(format(12.3456789, "E")) #1.234568E+01
print(format(12.3456785, "e")) #1.234568e+01
print(format(12.3456785, "E")) #1.234568E+01
print(format(12.34567851, "e")) #1.234568e+01
print(format(12.34567851, "E")) #1.234568E+01
“f"和”F“
print(format(123, "f")) #123.000000
print(format(123, "F")) #123.000000
print(format(12.3, "f")) #12.300000
print(format(12.3, "F")) #12.300000
print(format(12.3456789, "f")) #12.345679
print(format(12.3456789, "F")) #12.345679
print(format(12.3456785, "f")) #12.345678
print(format(12.3456785, "F")) #12.345678
print(format(12.34567851, "f")) #12.345679
print(format(12.34567851, "F")) #12.345679
”g“和”G“
print(format(123456, "g")) #123456
print(format(123456, "G")) #123456
print(format(123456.3, "g")) #123456
print(format(123456.3, "G")) #123456
print(format(123456.5, "g")) #123456
print(format(123456.5, "G")) #123456
print(format(123456.6, "g")) #123457
print(format(123456.6, "G")) #123457
print(format(1234567.6, "g")) #1.23457e+06
print(format(1234567.6, "G")) #1.23457E+06
print(format(1234562.6, "g")) #1.23456e+06
print(format(1234562.6, "G")) #1.23456E+06
print(format(123, "g")) #123
print(format(123, "G")) #123
print(format(123.45, "g")) #123.45
print(format(123.45, "G")) #123.45
print(format(12.3456189, "g")) #12.3456
print(format(12.3456189, "G")) #12.3456
print(format(12.34567851, "g")) #12.3457
print(format(12.34567851, "G")) #12.3457
print(format(12.34565, "g")) #12.3456
print(format(12.34565, "G")) #12.3456
print(format(12.345650, "g")) #12.3456
print(format(12.345650, "G")) #12.3456
print(format(12.345651, "g")) #12.3457
print(format(12.345651, "G")) #12.3457
print(format(12.3456501, "g")) #12.3457
print(format(12.3456501, "G")) #12.3457
”n"
print(format(123456, "n")) #123456
print(format(123456.3, "n")) #123456
print(format(123456.5, "n")) #123456
print(format(123456.6, "n")) #123457
print(format(1234567.6, "n")) #1.23457e+06
print(format(1234562.6, "n")) #1.23456e+06
print(format(123, "n")) #123
print(format(123.45, "n")) #123.45
print(format(12.3456189, "n")) #12.3456
print(format(12.34567851, "n")) #12.3457
print(format(12.34565, "n")) #12.3456
print(format(12.345650, "n")) #12.3456
print(format(12.345651, "n")) #12.3457
print(format(12.3456501, "n")) #12.3457
None:
print(format(123456, "")) #123456
print(format(123456.3, "")) #123456.3
print(format(123456.5, "")) #123456.5
print(format(123456.6, "")) #123456.6
print(format(1234567.6, "")) #1234567.6
print(format(1234562.6, "")) #1234562.6
print(format(123, "")) #123
print(format(123.45, "")) #123.45
print(format(12.3456189, "")) #12.3456189
print(format(12.34567851, "")) #12.34567851
print(format(12.34565, "")) #12.34565
print(format(12.345650, "")) #12.34565
print(format(12.345651, "")) #12.345651
print(format(12.3456501, "")) #12.3456501
24.frozenset([iterable]):不可变集合,具体可参考:https://blog.csdn.net/grace666/article/details/98752091
25.getattr(object, name[, default]):返回对象命名属性的值;object是对象,name 必须是字符串,如果name是对象的属性之一,则返回该属性的值;如果指定的属性不存在,但是提供了 default 值,则返回它;否则触发 AttributeError;如果给定的属性name是对象的方法,则返回的是函数对象,需要调用函数对象来获得函数的返回值,调用的话就是函数对象后面加括号,如func之于func()
class A():
bar=1
print(getattr(A, "bar")) #1
print(getattr(A, "bar","new")) #1
print(getattr(A, "bar1","默认")) #默认
# print(getattr(A, "bar1")) #报错:AttributeError: 'A' object has no attribute 'bar1'
a=A()
print(getattr(a, "bar")) #1
print(getattr(a, "bar","new")) #1
print(getattr(a, "bar1","默认")) #默认
# print(getattr(a, "bar1")) #报错:AttributeError: 'A' object has no attribute 'bar1'
注意,如果给定的方法func()是实例函数,则不能写getattr(A, 'func')(),因为fun()是实例函数的话,是不能用A类对象来调用的,应该写成getattr(A(), 'func')();实例函数和类函数的区别可以简单的理解一下,实例函数定义时,直接def func(self):,这样定义的函数只能是将类实例化后,用类的实例化对象来调用;而类函数定义时,需要用@classmethod来装饰,函数默认的参数一般是cls,类函数可以通过类对象来直接调用,而不需要对类进行实例化;
class A():
def p(self):
print("hello")
@classmethod
def q(cls):
print("world")
c=getattr(A, "p")
print(type(c)) #<class 'function'>
print(c) #<function A.p at 0x00000174D6AE9950>
# c() #报错:TypeError: p() missing 1 required positional argument: 'self'
a=A()
c=getattr(a, "p")
print(type(c)) #<class 'method'>
print(c) #<bound method A.p of <__main__.A object at 0x000002064A110A90>>
c() #hello
c=getattr(A, "q")
print(type(c)) #<class 'method'>
print(c) #<bound method A.q of <class '__main__.A'>>
c() #world
a=A()
c=getattr(a, "q")
print(type(c)) #<class 'method'>
print(c) #<bound method A.q of <class '__main__.A'>>
c() #world
26.globals():获取当前模块的全局变量,不受位置的影响,无论在是否在类或者方法中,都将返回调用它时当前模块的全局变量
在模块中直接使用:
print(globals()) #{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001AAFBB93080>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'pymongo': <module 'pymongo' from 'D:\\V3.7.0\\lib\\site-packages\\pymongo\\__init__.py'>, 'datetime': <module 'datetime' from 'D:\\\\V3.7.0\\lib\\datetime.py'>, 'reduce': <built-in function reduce>, 'ctime': <built-in function ctime>}
定义在变量内:
a="hello"
print(globals()) #{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000029A0FAE3080>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'pymongo': <module 'pymongo' from 'D:\\lib\\site-packages\\pymongo\\__init__.py'>, 'datetime': <module 'datetime' from 'D:\\\\V3.7.0\\lib\\datetime.py'>, 'reduce': <built-in function reduce>, 'ctime': <built-in function ctime>, 'a': 'hello'}
定义在方法内:
def f():
a=1
b=2
print(globals())
f() #{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001F9DFEC3080>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'pymongo': <module 'pymongo' from 'D:\\V3.7.0\\lib\\site-packages\\pymongo\\__init__.py'>, 'datetime': <module 'datetime' from 'D:\\lib\\datetime.py'>, 'reduce': <built-in function reduce>, 'ctime': <built-in function ctime>, 'f': <function f at 0x000001F9DFB5D1E0>}
27.hasattr(object, name):object是对象,name 必须是字符串,如果name是对象的属性之一,则返回True;否则返回False
class A():
bar=1
print(hasattr(A, "bar")) #True
print(hasattr(A, "bar1")) #False
a=A()
print(hasattr(a, "bar")) #True
print(hasattr(a, "bar1")) #False
class A():
def p(self):
print("hello")
@classmethod
def q(cls):
print("world")
c=hasattr(A, "p")
print(type(c)) #<class 'bool'>
print(c) #True
# c() #报错:TypeError: 'bool' object is not callable
a=A()
c=hasattr(a, "p")
print(type(c)) #<class 'bool'>
print(c) #True
c=hasattr(A, "q")
print(type(c)) #<class 'bool'>
print(c) #True
a=A()
c=hasattr(a, "q")
print(type(c)) #<class 'bool'>
print(c) #True
28.hash(object):如果object有哈希值的话,并返回,它们在字典查找元素时用来快速比较字典的键,相同大小的数字变量有相同的哈希值(即使它们类型不同,如 1 和 1.0)
print(hash("a")) #1662299966867198853
a="a"
print(hash(a)) #1662299966867198853
print(hash(1)) #1
print(hash(1.0)) #1
print(hash(1.00)) #1
class A():
pass
a=A()
print(hash(a)) #-9223371894822596443
print(hash(A)) #-9223371894822325386
# list1=[1,2]
# print(hash(list1)) #报错:TypeError: unhashable type: 'list'
# set1=set([1,2])
# print(hash(set1)) #报错:TypeError: unhashable type: 'set'
# dict1={"a":1}
# print(hash(dict1)) #报错:TypeError: unhashable type: 'dict'
class Test:
def __init__(self, i):
self.i = i
for i in range(10):
t = Test(1)
print(hash(t), id(t))
注:可应用于number、string和对象,不能直接应用于 list、set、dictionary;在 hash() 对对象使用时,所得的结果不仅和对象的内容有关,还和对象的 id(),也就是内存地址有关;可以让攻击者难以预测内置的set或者dict的一些行为,但远不足以承担真正的密码安全级别的hash的作用
29.id(object):返回对象的“标识值”(内存地址)。该值是一个整数,在此对象的生命周期中保证是唯一且恒定的。两个生命期不重叠的对象可能具有相同的 id() 值
a=1
b="a"
c=[1,2]
print(id(a)) #140708809987104
print(id(b)) #2006140491904
print(id(c)) #2006179152584
30.input([prompt]):如果存在 prompt 实参,则将其标准输出,末尾不带换行符。接下来,该函数从输入中读取一行,将其转换为字符串(除了末尾的换行符)并返回。当读取到 EOF 时,则触发 EOFError
s=input("--> ")
print(s)
# --> hello nihao
# hello nihao
s=input()
print(s)
print(type(s))
# 绝对舒服就多少
# 绝对舒服就多少
# <class 'str'>
注:如果加载了 readline 模块,input() 将使用它来提供复杂的行编辑和历史记录功能
31.int(x, base=10):返回一个使用数字或字符串 x 生成的整数对象
print(int(3)) #3
(1)若没有实参的时候返回 0
print(int()) #0
(2)对于浮点数,它向零舍入
print(int(3.2)) #3
print(int(3.5)) #3
print(int(3.9)) #3
(3)如果 x 定义了 __int__(),int(x) 返回 x.__int__() ;如果 x 定义了 __trunc__(),它返回 x.__trunc__() ;若x既定义了 __int__(),也定义了__trunc__(),貌似返回的是 x.__int__()
class A():
def __int__(self):
print("true aaa")
return 100 #若没定义,会报错:TypeError: __int__ returned non-int (type NoneType)
a=A()
int(a) #true aaa
print(int(a)) #true aaa
#100
class B():
def __trunc__(self):
print("true bbb")
return 500 #若没定义,会报错:TypeError: __int__ returned non-int (type NoneType)
b=B()
int(b) #true bbb
print(int(b)) #true bbb
#500
class C():
def __trunc__(self):
print("true kkk")
return 333 #若没定义,会报错:TypeError: __int__ returned non-int (type NoneType)
def __int__(self):
print("true aaa")
return 100 #若没定义,会报错:TypeError: __int__ returned non-int (type NoneType)
c=C()
int(c) #true aaa
print(int(c)) #true aaa
#100
(4)如果 x 不是数字,或者有 base 参数,x 必须是字符串、bytes、表示进制为 base 的 整数字面值 的 bytearray 实例。
# print(int("x")) #报错:ValueError: invalid literal for int() with base 10: 'x'
print(int("12",16)) #18
print(int("0xa",16)) #10
print(int("11", 10)) #11
(5)该文字前可以有 + 或 - (中间不能有空格),前后可以有空格;一个进制为 n 的数字包含 0 到 n-1 的数,其中 a 到 z (或 A 到 Z )表示 10 到 35;默认的 base 为 10 ,允许的进制有 0、2-36;2、8、16 进制的数字可以在代码中用 0b/0B 、 0o/0O 、 0x/0X 前缀来表示;进制为 0 将安照代码的字面量来精确解释,最后的结果会是 2、8、10、16 进制中的一个,所以 int('010', 0) 是非法的,但 int('010') 和 int('010', 8) 是合法的
print(int("+12",16)) #18
print(int("-12",16)) #-18
print(int(" +12 ",16)) #18
print(int("+0xa",16)) #10
print(int("-0xa",16)) #-10
print(int(" -0xa ",16)) #-10
print(int("+11", 10)) #11
print(int("-11", 10)) #-11
print(int(" -11 ", 10)) #-11
# print(int("010",0)) #报错:ValueError: invalid literal for int() with base 0: '010'
注:x 现在只能作为位置参数。
32.isinstance(object, classinfo):如果 object 实参是 classinfo 实参的实例,或者是(直接、间接或 虚拟)子类的实例,则返回 true。如果 classinfo 是对象类型(或多个递归元组)的元组,如果 object 是其中的任何一个的实例则返回 true。 如果 classinfo 既不是类型,也不是类型元组或类型的递归元组,那么会触发 TypeError 异常
33.issubclass(class, classinfo):如果 class 是 classinfo 的子类(直接、间接或虚拟的),则返回 true。classinfo 可以是类对象的元组,此时 classinfo 中的每个元素都会被检查。其他情况,会触发 TypeError 异常。
hello="Hello"
print("[Hello]是否是str类的实例:",isinstance(hello, str)) #True
print("[Hello]是否是object类的实例:",isinstance(hello, object)) #True
print("[Hello]是否是tuple类的实例:",isinstance(hello, tuple)) #False
print("[Hello]是否是(str,tuple,list)类的实例:",isinstance(hello, (str,tuple,list))) #True
# print("[Hello]是否是object类的实例:",isinstance(hello, [str,tuple,list])) #报错:TypeError: isinstance() arg 2 must be a type or tuple of types
# print("[Hello]是否是str类的子类:",issubclass(hello, str)) #报错:TypeError: issubclass() arg 1 must be a class
# print("[Hello]是否是str类的子类:",issubclass(hello, object)) #报错:TypeError: issubclass() arg 1 must be a class
print("[str]是否是str类的子类:",issubclass(str, str)) #True
print("[str]是否是str类的子类:",issubclass(str, object)) #True
print("[str]是否是str类的子类:",issubclass(str, tuple)) #False
print("[str]是否是str类的子类:",issubclass(str, (str,tuple,list))) #True
class A():
pass
a=A()
print("class[A]是否是A类的实例:",isinstance(A, A)) #False
print("class[A]是否是object类的实例:",isinstance(A, object)) #True
print("类实例[a]是否是A类的实例:",isinstance(a, A)) #True
print("类实例[a]是否是object类的实例:",isinstance(a, object)) #True
print("class[A]是否是A类的子类:",issubclass(A, A)) #True
print("class[A]是否是object类的子类:",issubclass(A, object)) #True
# print("类实例[a]是否是A类的子类:",issubclass(a, A)) #报错:TypeError: issubclass() arg 1 must be a class
# print("类实例[a()]是否是A类的子类:",issubclass(a(),A)) #报错:TypeError: 'A' object is not callable
# print("类实例[a()]是否是object类的子类:",issubclass(a(),object)) #报错:TypeError: 'A' object is not callable
class B():
pass
class C(A,B):
pass
c=C()
print("类实例[c]是否是A类的实例:",isinstance(c, A)) #True
print("类实例[c]是否是B类的实例:",isinstance(c, B)) #True
print("类实例[c]是否是object类的实例:类的实例:",isinstance(c, C)) #True
print("类实例[c]是否是object类的实例:",isinstance(c, object)) #True
print("class[C]是否是A类的实例:",isinstance(C, A)) #False
print("class[C]是否是B类的实例:",isinstance(C, B)) #False
print("class[C]是否是C类的实例:",isinstance(C, C)) #False
print("class[C]是否是object类的实例:",isinstance(C, object)) #True
print("class[C]是否是A类的子类:",issubclass(C, A)) #True
print("class[C]是否是B类的子类:",issubclass(C, B)) #True
print("class[C]是否是C类的实例:类的子类:",issubclass(C, C)) #True
print("class[C]是否是object类的子类:",issubclass(C, object)) #True
通过上面程序可以看出,issubclass() 和 isinstance() 两个函数的用法差不多,区别是:(1) issubclass() 的第一个参数是类名,isinstance() 的第一个参数是变量,因此:issubclass 用于判断是否为子类,而 isinstance() 用于判断是否为该类或子类的实例;(2)issubclass() 和 isinstance() 两个函数的第二个参数都可使用元组。
34.iter(object[, sentinel]):返回一个iterator对象;该方法的第一个参数object的参数类型,是根据有无第二个参数sentinel决定-->若没有sentinel,object 必须是支持迭代协议(有 __iter__() 方法)的集合对象,或必须支持序列协议(有 __getitem__() 方法,且数字参数从 0 开始),如果它不支持这些协议,会触发 TypeError;如果有sentinel,那么 object 必须是可调用的对象(如,函数)。这种情况下生成的迭代器,每次迭代调用它的 __next__() 方法时都会不带实参地调用 object;如果返回的结果等于sentinel,则触发 StopIteration,否则返回调用结果
lst=[1,2,3,4,5]
for i in iter(lst):
print(i) #1
#2
#3
#4
#5
# for i in iter(lst,3): #报错:TypeError: iter(v, w): v must be callable
# print(i)
from random import randint
cnt=1
# guess(3)
def guess():
return(randint(0,10))
print(type(iter(guess,5))) #<class 'callable_iterator'>
print(type(iter("sdfdf"))) #<class 'str_iterator'>
for i in iter(guess,5):
print("Yes,第%s次猜测的数字是 : %s"%(cnt,i))
cnt+=1
35.len(s):返回对象s的长度(元素个数)。s可以是序列(如 string、bytes、tuple、list 或 range 等)或集合(如 dictionary、set 或 frozen set 等)
str1="abcde"
print(len(str1)) #5
byte1=b"123"
print(len(byte1)) #3
tuple1=(1,2,3,4,5)
print(len(tuple1)) #5
list1=[1,2,3,"a",(1,2)]
print(len(list1)) #5
range1=range(1,8)
print(len(range1)) #7
dict1={"a":1,"b":2}
print(len(dict1)) #2
set1={1,2,1,3}
print(len(set1)) #3
36.locals():返回当前环境的局部变量
# 1.本地
print(locals()) #{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000017C7FEF3080>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'pymongo': <module 'pymongo' from 'D:\\Program Files (x86)\\Python\\V3.7.0\\lib\\site-packages\\pymongo\\__init__.py'>, 'datetime': <module 'datetime' from 'D:\\Program Files (x86)\\Python\\V3.7.0\\lib\\datetime.py'>, 'reduce': <built-in function reduce>, 'ctime': <built-in function ctime>}
# 2.方法中
out=1
def run1(inside):
print(locals())
# 结果中只有inside一个参数,它无法在方法体内获取到外面的全局变量out
run1(3) #{'inside': 3}
def run(inside1,inside2):
print(locals())
run(8,7) #{'inside1': 8, 'inside2': 7}
# 3.类方法中
class A():
a=1
b=2
print(locals()) #{'__module__': '__main__', '__qualname__': 'A', 'a': 1, 'b': 2}
def run(self):
print(locals())
a=A()
#结果只有self,甚至连类声明的属性a和b都是无法获取到的
a.run() #{'self': <__main__.A object at 0x000001D0621B0A58>}
37.map(function, iterable, ...):返回一个将 function 应用于 iterable(iterable开始,其后的都是可迭代对象,列表,元祖,迭代器等,换句话说:能执行 for x in param:语句的都可以)中每一项并输出其结果的迭代器。 如果传入了额外的 iterable 参数,function 必须接受相同个数的实参并被应用于从所有可迭代对象中并行获取的项,即,map参数个数为x个,function个数为x-1个,否则会报错
def f1(x):
return x*x
list1=[1,2,3,4,5]
list2=[6,7,8,9,10,11,12]
list3=[20,21,22,23]
list4=[1,2,3]
list5=[6,7]
list6=[20]
square=list(map(lambda x:x**2,list1))
print(square) #[1, 4, 9, 16, 25]
tuple1=(1,2,3,4,5)
square=list(map(lambda x:x**2,tuple1))
print(square) #[1, 4, 9, 16, 25]
print(map(f1,list1)) #<map object at 0x000001F0E5670A58>
print(list(map(f1,list1))) #[1, 4, 9, 16, 25]
print(tuple(map(f1,list1))) #(1, 4, 9, 16, 25)
当有多个可迭代对象时,最短的可迭代对象耗尽则整个迭代就将结束
def f2(x,y,z):
return x+y+z
# print(list(map(f2,list1))) #报错:TypeError: f2() missing 2 required positional arguments: 'y' and 'z'
print(list(map(f2,list1,list2,list3))) #[27, 30, 33, 36]
print(list(map(f2,list4,list5,list6))) #[27]
38.max(iterable, *[, key, default])
max(arg1, arg2, *args[, key]):返回可迭代对象中最大的元素;默认数值型参数,取值大者;字符型参数,取字母表排序靠后者;还可以传入命名参数key,其为一个函数,用来指定取最大值的方法;default命名参数用来指定最大值不存在时返回的默认值
(1)只传入一个参数,该参数必须为可迭代的对象,不能为空
print(max("123")) #3
print(max({'x':1,'y':2,'z':10})) #z
print(max(list1)) #5
print(max(list2)) #12.1
print(max(tuple1)) #4
(2)当传入参数数据类型不一致时,传入的参数会进行隐式数据类型转换,如果不能进行隐式转换就会报错
# print(max(1,"a")) #报错:TypeError: '>' not supported between instances of 'str' and 'int'
print(max(list1,list2)) #[6, 7, 8, 9, 10, 11, 12, 12.1]
print(max(list1,list7)) #[1, 2, 3, 4, 5, 5.0]
print(max(list1,list8)) #[1, 2, 3, 4, 5, 5.0]
print(max(list1,list9)) #[1, 2, 3, 4, 5, 5.0]
(3)当存在多个相同的最大值时,返回的是最先出现的那个最大值
a=[1,2]
b=[1,1]
c=[1,2]
print(id(a)) #2191192589320
print(id(b)) #2191194430024
print(id(c)) #2191193972168
d=max(a,b,c)
print(d) #[1, 2]
print(id(d)) #2191192589320
print(id(a)==id(d)) #True
print(id(c)==id(d)) #False
(4)可以传入命名参数 key,指定取最大值的方法
print(max(-1,-5)) #-1
print(max(-1,-5,key=abs)) #-5
key另一个作用是:原本数据类型不一致,不能进行比较的,传入适当的key就可以比较
print(max([1,2],(2,3),key=lambda x:x[1])) #(2, 3)
(5)空的可迭代对象不能进行比较,必须传入一个默认值,否则会触发ValueError
# # print(max(())) #报错:ValueError: max() arg is an empty sequence
# # # print(max([])) #报错:ValueError: max() arg is an empty sequence
print(max((),default=1)) #1
print(max((),default=0)) #0
默认值必须用命名参数进行传参,否会被认为是一个比较的元素
# print(max((),1)) #报错TypeError: '>' not supported between instances of 'int' and 'tuple'
39.memoryview(obj):返回由obj创建的“内存视图”对象,memoryview对象允许 Python 代码访问一个对象的内部数据,只要该对象支持“缓冲区协议”,而无需进行拷贝;支持缓冲区协议的内置对象包括 bytes 和 bytearray
# 1.不使用memoryview
a=bytearray(b"aaaaa")
b=a[:2]
print(b) #bytearray(b'aa')
print(id(a[:2])) #2386588274224
print(id(b)) #2386588273160
b[:2]=b"bb"
print(a) #bytearray(b'aaaaa')
print(b) #bytearray(b'bb')
# 2.使用memoryview
a=bytearray(b"aaaaa")
ma=memoryview(a)
print(ma.readonly) #False
mb=ma[:2]
mb[:2]=b"bb"
print(ma.tobytes()) #b'bbaaa'
print(mb.tobytes()) #b'bb'
str和bytearray的切片操作会产生新的切片str和bytearry并拷贝数据,使用memoryview之后不会
40.min(iterable, *[, key, default])
min(arg1, arg2, *args[, key]):返回可迭代对象中最小的元素;默认数值型参数,取值小者;字符型参数,取字母表排序靠前者;还可以传入命名参数key,其为一个函数,用来指定取最小值的方法;default命名参数用来指定最小值不存在时返回的默认值
(1)只传入一个参数,该参数必须为可迭代的对象,不能为空
print(min("123")) #1
print(min({'x':1,'y':2,'z':10})) #x
print(min(list1)) #1
print(min(list2)) #6
print(min(tuple1)) #1
(2)当传入参数数据类型不一致时,传入的参数会进行隐式数据类型转换,如果不能进行隐式转换就会报错
print(min(1,"a")) #报错:TypeError: '<' not supported between instances of 'str' and 'int'
print(min(list1,list2)) #[1, 2, 3, 4, 5, 5.0]
print(min(list1,list7)) #[1, 2, 3, 4, 5]
print(min(list1,list8)) #[1, 2, 3, 4, 5, 5.0]
print(min(list1,list9)) #[1, 2, 3, 4, 5, -1]
(3)当存在多个相同的最小值时,返回的是最先出现的那个最小值
a=[1,1]
b=[1,2]
c=[1,1]
print(id(a)) #2264057461384
print(id(b)) #2264057461896
print(id(c)) #2264057416008
d=min(a,b,c)
print(d) #[1, 1]
print(id(d)) #2264057461384
print(id(a)==id(d)) #True
print(id(c)==id(d)) #False
(4)可以传入命名参数 key,指定取最小值的方法
print(min(-1,-5)) #-5
print(min(-1,-5,key=abs)) #-1
key另一个作用是:原本数据类型不一致,不能进行比较的,传入适当的key就可以比较
print(min([1,2],(2,3),key=lambda x:x[1])) #[1, 2]
(5)空的可迭代对象不能进行比较,必须传入一个默认值,否则会触发ValueError
# print(min(())) #报错:ValueError: min() arg is an empty sequence
# print(min([])) #报错:ValueError: min() arg is an empty sequence
print(min((),default=1)) #1
print(min((),default=0)) #0
默认值必须用命名参数进行传参,否会被认为是一个比较的元素
# print(min((),1)) #报错:TypeError: '<' not supported between instances of 'int' and 'tuple'
41.next(iterator[, default]):通过调用iterator 的 __next__() 方法获取下一个元素;如果迭代器耗尽,则返回给定的 default,如果没有default,则触发 StopIteration
s1="abc"
a=iter(s1)
print(next(a)) #a
print(next(a)) #b
print(next(a)) #c
# print(next(a)) #报错:StopIteration
s1="abc"
a=iter(s1)
print(next(a)) #a
print(next(a)) #b
print(next(a)) #c
print(next(a,"默认值1")) #默认值1
print(next(a,"默认值2")) #默认值2
print(next(a,"默认值3")) #默认值3
42.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):打开 file 并返回对应的 file object。如果该文件不能打开,则触发 OSError
(1)file:表示将要打开的文件的路径(绝对路径或者当前工作目录的相对路径),也可以是要被封装的整数类型文件描述符;如果是文件描述符,它会随着返回的 I/O 对象关闭而关闭,除非 closefd 被设为 False ;
(2)mode:指定打开文件的模式,默认值是 'r' ,如下图,具体不同mode值不同的意义

用流程图表示:

#“r”
with open(file_path,"r") as f:
data=f.readlines()
print(data) #['aaa\n', '的说法就是懒得加发烧\n', '沙发上地方\n', '地方开始发鸡蛋的\n', '\n', '打开方式\n', '独守空房\n', '收发点']
f.close()
#"w",文件会先被清空
with open(file_path,"w") as f:
# data=f.readlines() #报错:io.UnsupportedOperation: not readable
f.writelines(text1)
f.writelines(text2)
with open(file_path) as f:
data=f.readlines()
print(data) #['abc\n', '但是\n']
f.close()
# "x"
with open(file_path,"x") as f: #报错:FileExistsError: [Errno 17] File exists: 'F:\\/test.txt'
with open(file_path1,"x") as f:
f.writelines(text1)
f.writelines(text2)
with open(file_path) as f:
data=f.readlines()
print(data) #['abc\n', '但是\n']
f.close()
#"a"
with open(file_path,"a",encoding="utf-8") as f:
f.writelines(text1)
f.writelines(text2)
with open(file_path,encoding="utf-8") as f:
data=f.readlines()
print(data) #['锄禾日当午,汗滴禾下土。\n', 'abc\n', '但是\n']
f.close()
#"a+"
with open(file_path,"a+",encoding="utf-8",buffering=1) as f:
f.writelines(text1)
f.writelines(text2)
with open(file_path,encoding="utf-8") as f:
data=f.readlines()
print(data) #['锄禾日当午,汗滴禾下土。\n', 'abc\n', '但是\n']
f.close()
#"r+"
with open(file_path,"r+",encoding="utf-8") as f:
f.writelines(text1)
f.writelines(text2)
data=f.readlines() #开始一直在这报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 13: invalid start byte
#将文件另存为,把编码格式改为“utf-8”即可
print(data) #['\ufeff锄禾日当午,汗滴禾下土。\n']
f.close()
(3)buffering:是一个可选的整数,用于设置缓冲策略。传递0以切换缓冲关闭(仅允许在二进制模式下),1选择行缓冲(仅在文本模式下可用),并且>1的整数以指示固定大小的块缓冲区的大小(以字节为单位)。如果没有给出 buffering 参数,则默认缓冲策略的工作方式如下:
1)二进制文件以固定大小的块进行缓冲;使用启发式方法选择缓冲区的大小,尝试确定底层设备的“块大小”或使用 io.DEFAULT_BUFFER_SIZE。在许多系统上,缓冲区的长度通常为4096或8192字节
2)“交互式”文本文件( isatty() 返回 True 的文件)使用行缓冲。其他文本文件使用上述策略用于二进制文件
(4)encoding:是用于解码或编码文件的编码的名称,这应该只在文本模式下使用
(5)errors:是一个可选的字符串参数,用于指定如何处理编码和解码错误 ,但不能在二进制模式下使用
(6)newline:区分换行符,可以是 None,'','\n','\r' 和 '\r\n'
(7)closefd :如果 closefd 是 False 并且给出了文件描述符而不是文件名,那么当文件关闭时,底层文件描述符将保持打开状态;如果给出文件名则 closefd 必须为 True (默认值),否则将引发错误
(8)opener:可以通过传递可调用的 opener 来使用自定义开启器。然后通过使用参数( file,flags )调用 opener 获得文件对象的基础文件描述符。 opener 必须返回一个打开的文件描述符(使用 os.open as opener 时与传递 None 的效果相同)。
43.pow(base, exp[, mod]):返回的是base的 exp 次幂, pow(base, exp) 等价于base**exp
print(pow(2,3)) #8
print(pow(2,-3)) #0.125
print(pow(2,1.3)) #2.4622888266898326
print(pow(1.2,3)) #1.7279999999999998
(1)对于 int 操作数 base 和 exp,如果mod存在,则返回 base 的 exp 次幂对 mod 取余(比 pow(base, exp) % mod 更高效),但是mod必须为整数,不能为0,并且base和exp都必须为整数
print(pow(2,3,4)) #0
# print(pow(2,3,0)) #报错:ValueError: pow() 3rd argument cannot be 0
print(pow(2,3,-4)) #0
print(pow(2,3,1.1)) #报错:TypeError: pow() 3rd argument not allowed unless all arguments are integers
print(pow(-2,3,-4)) #0
# print(pow(2,3,1.1)) #报错:TypeError: pow() 3rd argument not allowed unless all arguments are integers
# print(pow(2,1.3,4)) #报错:TypeError: pow() 3rd argument not allowed unless all arguments are integers
(2)在3.7版本中,如果给出 mod,则exp不能为负数,否则报错
# print(pow(2,-3,4)) #报错:ValueError: pow() 2nd argument cannot be negative when 3rd argument specified
# print(pow(2,-3,-4)) #报错:ValueError: pow() 2nd argument cannot be negative when 3rd argument specified
# print(pow(2,-3,-4)) #报错:ValueError: pow() 2nd argument cannot be negative when 3rd argument specified
# print(pow(-2,-3,-4)) #报错:ValueError: pow() 2nd argument cannot be negative when 3rd argument specified
# print(pow(2,-3,3)) #报错:ValueError: pow() 2nd argument cannot be negative when 3rd argument specified
# print(pow(9,-3,3)) #报错:ValueError: pow() 2nd argument cannot be negative when 3rd argument specified
注:
(1)在 3.8 版更改:对于 int 操作数,三参数形式的 pow 现在允许第二个参数为负值,即可以计算倒数的余数;如果给出 mod 并且 exp 为负值,则 base 必须相对于 mod 不可整除。 在这种情况下,将会返回 pow(inv_base, -exp, mod),其中 inv_base 为 base 的倒数对 mod 取余
(2)在 3.9 版更改:允许关键字参数。 之前只支持位置参数
44.print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False):file如果给出,将 objects 打印到 file 指定的文本流,以 sep 分隔并在末尾加上 end;否则就打印到屏幕上
print("A","b","c") #A b c
print("A","b","c", sep=' ** ') #A ** b ** c
print("A","b","c", end=' !!\n') #A b c !!
print("A","b","c", sep=' ** ', end=' !!\n') #A ** b ** c !!
(1)sep, end, file 和 flush 如果存在,必须以关键字参数的形式给出
(2)所有非关键字参数(object)都会被转换为字符串,会被写入到流,以sep且在末尾加上 end,sep 和 end 都必须为字符串;它们也可以为 None,即,使用默认值
(3)如果没有给出 objects,则 print() 将只写入 end
print(sep=' ** ') #
print(end=' !!\n') # !!
print(sep=' ** ', end=' !!\n') # !!
(4)file 参数必须是一个具有 write(string) 方法的对象;如果参数不存在或为 None,则将使用 sys.stdout,但如果使用了file,待打印文本就会输出到指定文件,而不是打印到屏幕上
print("A","b","c", sep=' ** ', end=' !\n', file=open('1.txt', 'w'),flush=True)
print(open('1.txt', 'r').read()) #A ** b ** c !
(5)由于要打印的参数会被转换为文本字符串,因此 print() 不能用于二进制模式的文件对象。 对于这些对象,应改用 file.write(...)
(6)输出是否被缓存通常决定于 file,但如果 flush 关键字参数为真值,流会被强制刷新。
在 3.3 版更改: 增加了 flush 关键字参数。
45.class property(fget=None, fset=None, fdel=None, doc=None):在新式类中返回属性值,其中,fget 是获取属性值的函数,fset 是用于设置属性值的函数,fdel 是用于删除属性值的函数,并且 doc 为属性对象创建文档字符串。
这么说明比较抽象,拿个例子来说:一般我们写类的时候,对于属性如果直接暴露出去,虽然写法简单,但是对于参数无法进行检查:
#无法检查参数,可随意改
class Goods:
def __init__(self):
self.p = 18
obj=Goods()
print(obj.p) #18
obj.p="aa"
print(obj.p) #aa
为了限制price的范围,可以通过一个set_price()方法来设置价格,再通过一个get_price()来获取价格,这样,在set_price()方法里,就可以检查参数:
class Goods(object):
def __init__(self):
self._p=100
# pass
def get_price(self):
return self._p
def set_price(self,value):
if not isinstance(value,int):
raise ValueError("价格必须为整数")
self._p=value
def del_price(self):
del self._p
# PRICE=property(get_price,set_price,del_price,"价格属性的描述。。。")
obj=Goods()
print(obj.get_price()) #100
obj.set_price(200)
print(obj.get_price()) #200
obj.set_price("abc")
# print(obj.get_price()) #报错:raise ValueError("价格必须为整数") ValueError: 价格必须为整数
但是,上面的调用方法又略显复杂,没有直接用属性这么直接简单,对于类的方法,装饰器一样起作用。Python内置的@property装饰器就是负责把一个方法变成属性调用的:
class Goods:
def __init__(self):
self._p = 18
@property
def price(self): # 读取
"""属性属性属性"""
return self._p
# 方法名.setter
@price.setter # 设置,仅可接收除self外的一个参数,必须加上“price.”,否则报错:NameError: name 'setter' is not defined
def price(self, value):
if not isinstance(value,int):
raise ValueError("价格必须为整数")
self._p = value
# 方法名.deleter
@price.deleter # 删除
def price(self):
del self._p
obj=Goods()
print(obj.price) #18
obj.price=22
print(obj.price) #22
# obj.price="a"
# print(obj.price) #报错:raise ValueError("价格必须为整数") ValueError: 价格必须为整数
del obj.price
# print(obj.price) #报错:AttributeError: 'Goods' object has no attribute '_p'
把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@price.setter
46.range(stop)
range(start, stop[, step]):迭代器,为不可变的数字序列
(1)当只提供1个参数时,为stop,start默认为0
print(list(range(10))) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
(2)提供2个参数时,为start和stop,step默认为1
print(list(range(0,10))) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(1,10))) #[1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10,1))) #[]
print(list(range(10,2))) #[]
(3)提供3个参数时,如果step为0会触发异常
print(list(range(0,10,1))) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(0,10,2))) #[0, 2, 4, 6, 8]
print(list(range(0,-10,-1))) #[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
# print(list(range(0,10,0))) #报错 ValueError: range() arg 3 must not be zero
(4)提供如包含检测、元素索引查找、切片等特性,并支持负索引
r=range(0,20,2)
print(11 in r) #False
print(10 in r) #True
print(r.index(6)) #3
print(r[-1]) #18
(5)使用 == 和 != 检测 range 对象是否相等是将其作为序列来比较;如果两个 range 对象表示相同的值序列就认为它们是相等的(注:比较结果相等的两个 range 对象可能会具有不同的 start, stop 和 step 属性)
print(list(range(0))) #[]
print(list(range(2,1,3))) #[]
print((range(0)==range(2,1,3))) #True
print((range(0,3,2)==range(0,4,2))) #True
print((range(0,3,2)!=range(0,4,2))) #False
(6)range 类型相比常规 list 或 tuple 的优势在于一个 range 对象总是占用固定数量的(较小)内存,不论其所表示的范围有多大(因为它只保存了 start, stop 和 step 值,并会根据需要计算具体单项或子范围的值)
47.repr(object):返回包含一个对象的可打印表示形式的字符串, 对于许多类型来说,该函数会尝试返回的字符串将会与该对象被传递给 eval() 时所生成的对象具有相同的值
s="abc"
# print(eval(s)) #报错NameError: name 'abc' is not defined
print(eval(repr(s))) #abc
48.reversed(seq):返回一个反向的 iterator,原seq并不会改变
s="abcde"
print(list(reversed(s))) #['e', 'd', 'c', 'b', 'a']
print(reversed(s)) #<reversed object at 0x000001B6080FCF28>
print(s) #abcde
(1) 若序列反转赋值,第2次打印序列,会有空的现象
s="aefgt"
print(list(reversed(s))) #['t', 'g', 'f', 'e', 'a']
print(list(reversed(s))) #['t', 'g', 'f', 'e', 'a']
s="aefgt"
ss=reversed(s)
print(s) #aefgt
print(list(ss)) #['t', 'g', 'f', 'e', 'a']
print(list(ss)) #[]
#其原因就是ss不是反转列表本身,而是一个列表反向迭代器。所以当你第一次调用列表(ss),它会遍历ss并且创建一个新的列表从项目输出迭代器。当你再进行一次,ss仍然是原来的迭代器,已经经历了所有的项目,所以它不会再遍历什么,这就造成了空列表
即,reversed()赋值后,只在第一次遍历时返回值
(2)seq 若无__reversed__() 方法的对象,则必须是支持该序列协议(具有从 0 开始的整数类型参数的 __len__() 方法和 __getitem__() (object.__getitem__(self, key)以实现 self[key] 的求值)方法)
class MySeq():
def __len__(self):
return 6
def __getitem__(self, key):
return 'y{0}'.format(key)
print(MySeq()[3]) #y3
for item in reversed(MySeq()):
print(item, end=', ') #y5, y4, y3, y2, y1, y0,
(3)也可以自定义重写该方法
class MySeq():
def __len__(self):
return 6
def __getitem__(self, index):
return 'y{0}'.format(index)
class MyReversed(MySeq):
def __reversed__(self):
return reversed('hello, bright!')
for item in reversed(MyReversed()):
print(item, end=' ') #! t h g i r b , o l l e h
(4)如果reversed()的参数不是一个序列对象,我们应该为该对象定义一个__reversed__方法,这个时候就可以使用reversed()函数
class MyScore:
def __init__(self, name, *args):
self.name = name
self.scores = []
for value in args:
self.scores.append(value)
def __reversed__(self):
self.scores = reversed(self.scores)
x = MyScore("Ann", 66, 77, 88, 99, 100)
print('我的名字: {0}, 我的成绩: {1}'.format(x.name, x.scores)) #我的名字: Ann, 我的成绩: [66, 77, 88, 99, 100]
print('我的成绩按倒序排列:{}'.format(list(reversed(x.scores)))) #我的成绩按倒序排列:[100, 99, 88, 77, 66]
49.round( x [, n] ):返回浮点数x的四舍五入值,其中n默认为0,表示精度
a=123
print(round(a)) #123
a=123.4
print(round(a)) #123
a=123.5
print(round(a)) #124
a=123.6
print(round(a)) #124
a=123.9
print(round(a)) #124
a=123.11
print(round(a)) #123
a=123.15
print(round(a)) #123
a=123.51
print(round(a)) #124
a=123.55
print(round(a)) #124
a=123.11
print(round(a,1)) #123.1
a=123.15
print(round(a,1)) #123.2
a=123.51
print(round(a,1)) #123.5
a=123.55
print(round(a,1)) #123.5
a=123.56
print(round(a,1)) #123.6
a=123.541
print(round(a,1)) #123.5
a=123.545
print(round(a,1)) #123.5
a=123.549
print(round(a,1)) #123.5
a=123.551
print(round(a,1)) #123.6
a=123.555
print(round(a,1)) #123.6
a=123.559
print(round(a,1)) #123.6
a=123.541
print(round(a,2)) #123.54
a=123.545
print(round(a,2)) #123.55
a=123.549
print(round(a,2)) #123.55
a=123.551
print(round(a,2)) #123.55
a=123.555
print(round(a,2)) #123.56
a=123.559
print(round(a,2)) #123.56
a=123.5414
print(round(a,3)) #123.541
a=123.5415
print(round(a,3)) #123.541
a=123.5419
print(round(a,3)) #123.542
a=123.54145
print(round(a,3)) #123.541
a=123.54146
print(round(a,3)) #123.541
a=123.54149
print(round(a,3)) #123.541
50.setattr(object, name, value):用于设置属性值,该属性不一定是存在的
class A():
bar=1
print(getattr(A, "bar")) #1
setattr(A, "bar","new")
print(getattr(A, "bar")) #new
setattr(A, "aa","hahaha")
print(getattr(A, "aa")) #hahaha
a=A()
print(getattr(a, "bar")) #new
setattr(a, "bar","newnew")
print(getattr(a, "bar")) #newnew
setattr(a, "aa","dododo")
print(getattr(a, "aa")) #dododo
(1)针对类,如果getattr方法是传参形式,setattr不起效
class A():
def p(self):
print("hello")
@classmethod
def q(cls):
print("world")
a=A()
c=getattr(a, "p")
c() #hello
setattr(A, "p","xinpp")
print(getattr(a, "p")) #xinpp
c() #hello
c=getattr(A, "q")
c() #world
setattr(A, "q","xinq")
c() #world
print(getattr(A, "q")) #xinq
51.class slice(stop)
class slice(start, stop[, step]):实现切片对象,主要用在切片操作函数里的参数传递,其中,start -- 起始位置,stop -- 结束位置,step -- 间距
myslice=slice(3)
print(myslice) #slice(None, 3, None)
L=[1,2,3,4,5,6,7,8,9,10]
print(L[myslice]) #[1, 2, 3]
print(L[0:3]) #[1, 2, 3]
myslice=slice(1,7,2)
print(L[myslice]) #[2, 4, 6]
print(L[1:7:2]) #[2, 4, 6]
52.sorted(iterable, *, key=None, reverse=False):排序,返回新的排序列表,不会改变原对象,具体可见https://blog.csdn.net/grace666/article/details/103261144
53.@staticmethod:将方法转换为静态方法,静态方法不会接收隐式的第一个参数。要声明一个静态方法,具体可见https://blog.csdn.net/grace666/article/details/100990469
54.class str(object='')
class str(object=b'', encoding='utf-8', errors='strict'):返回 object 的 字符串 版本
(1)如果未提供 object 则返回空字符串
s1=str()
print(s1)
(2)如果 encoding 或 errors 均未给出,str(object) 返回 object.__str__(),这是 object 的“非正式”或格式良好的字符串表示。 对于字符串对象,这是该字符串本身。 如果 object 没有 __str__() 方法,则 str() 将回退为返回 repr(object)--具体可参考https://blog.csdn.net/grace666/article/details/103334640
(3)如果 encoding 或 errors 至少给出其中之一,则 object 应该是一个 bytes-like object (例如 bytes 或 bytearray)。 在此情况下,如果 object 是一个 bytes (或 bytearray) 对象,则 str(bytes, encoding, errors) 等价于 bytes.decode(encoding, errors)。 否则的话,会在调用 bytes.decode() 之前获取缓冲区对象下层的 bytes 对象
s1=b'Zoot!'
print(str(s1)) #b'Zoot!'
s1="aaa"
print(str(s1,encoding="utf-8")) #报错;TypeError: decoding str is not supported
s1=b"aaa"
print(str(s1,encoding="utf-8")) #aaa
55.sum(iterable, /, start=0):从 start 开始自左向右对 iterable 的项求和并返回总计值。 iterable 的项通常为数字,而start是指定相加的参数,默认为0
l1=[1,2,3,4,5]
print(sum(l1)) #15
print(sum(l1,1)) #16
t1=(1,2,3,4,5)
print(sum(t1)) #15
print(sum(t1,1)) #16
d1={1,2,3,4,5}
print(sum(d1)) #15
print(sum(d1,1)) #16
56.super([type[, object-or-type]]):返回一个代理对象,它会将方法调用委托给 type 的父类或兄弟类
(1)单继承,主要用来调用父类的方法
class A:
def __init__(self):
self.n=2
def plus(self,m):
print("A类的plus方法")
self.n+=m
class B(A):
def __init__(self):
self.n=3
def plus(self,m):
print("B类的plus方法")
super().plus(m)
self.n+=3
b=B()
b.plus(5) #B类的plus方法
#A类的plus方法
print(b.n) #11
super() 只传递一个参数时,是一个不绑定的对象,不绑定的话它的方法是不会有用的
(2)多重继承
class A:
def __init__(self):
self.n=2
def plus(self,m):
print("A类的plus方法")
self.n+=m
class B(A):
def __init__(self):
self.n=3
def plus(self,m):
print("B类的plus方法")
super().plus(m)
self.n+=4
class C(B):
def __init__(self):
self.n=5
def plus(self,m):
print("C类的plus方法")
super().plus(m)
self.n+=6
class D(C):
def __init__(self):
self.n=7
def plus(self,m):
print("D类的plus方法")
super().plus(m)
self.n+=8
d=D()
d.plus(5) #D类的plus方法
#C类的plus方法
#B类的plus方法
#A类的plus方法
print(d.n) #30
print(D.mro()) #[<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
(3)多继承
class A:
def __init__(self):
self.n=2
def plus(self,m):
print("A类的plus方法")
self.n+=m
class B(A):
def __init__(self):
self.n=3
def plus(self,m):
print("B类的plus方法")
super().plus(m)
self.n+=4
class C(A):
def __init__(self):
self.n=5
def plus(self,m):
print("C类的plus方法")
super().plus(m)
self.n+=6
class D(B,C):
def __init__(self):
self.n=7
def plus(self,m):
print("D类的plus方法")
super().plus(m)
self.n+=8
d=D()
d.plus(5) #D类的plus方法
#B类的plus方法
#C类的plus方法
#A类的plus方法
print(d.n) #30
print(D.mro()) #[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
以上可总结为:调用了父类的方法,出入的是子类的实例对象;新式类子类(A,B),A就在B之前进行搜索;super是一种类,类似于嵌套的一种设计,当代码执行到super实例化后,先去找同级父类,若没有其余父类,再执行自身父类,再往下走;所有类不重复调用,从左到右
(4)super(type):只传递一个参数的时候,是一个不绑定的对象,其方法是不会有用的
如下例子,只是执行了D的init方法
class Base:
def __init__(self):
print('Base.__init__')
class A(Base):
def __init__(self):
super().__init__()
print('A.__init__')
class B(Base):
def __init__(self):
super().__init__()
print('B.__init__')
class C(Base):
def __init__(self):
super().__init__()
print('C.__init__')
class D(A, B, C):
def __init__(self):
super(B).__init__() # 值传递一个参数,无论传A/B/C/D,都只执行了D的init方法
print('D.__init__')
D() #D.__init__
print(D.mro()) #[<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.Base'>, <class 'object'>]
(5)super(type,obj):传递两个参数的时候,如果第二个参数为一个对象,则 isinstance(obj, type) 必须为真值,如果 object-or-type 的 __mro__ 为 D -> B -> C -> A -> object 并且 type 的值为 B,则 super() 将会搜索 C -> A -> object
class Base:
def __init__(self):
print('Base.__init__')
class A(Base):
def __init__(self):
super().__init__()
print('A.__init__')
class B(Base):
def __init__(self):
super().__init__()
print('B.__init__')
class C(Base):
def __init__(self):
super().__init__()
print('C.__init__')
class D(A, B, C):
def __init__(self):
super(B,self).__init__() # 值传递一个参数
print('D.__init__')
D() #Base.__init__
#C.__init__
#D.__init__
print(D.mro()) #[<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.Base'>, <class 'object'>]
(6)super(type1,type2):传递两个参数的时候,如果第二个参数为一个类型,则 issubclass(type2, type) 必须为真值,如果 object-or-type 的 __mro__ 为 D -> B -> C -> A -> object 并且 type 的值为 B,则 super() 将会搜索 C -> A -> object
class Base:
def __init__(self):
print('Base.__init__')
class A(Base):
def __init__(self):
super().__init__()
print('A.__init__')
class B(Base):
def __init__(self):
super().__init__()
print('B.__init__')
class C(Base):
def __init__(self):
super().__init__()
print('C.__init__')
class D(A, B, C):
def __init__(self):
super(B,D).__init__(self) # D是B的子类,并且需要传递一个参数
print('D.__init__')
D() #Base.__init__
#C.__init__
#D.__init__
print(D.mro()) #[<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.Base'>, <class 'object'>]
class Base:
def __init__(self):
print('Base.__init__')
class A(Base):
def __init__(self):
super().__init__()
print('A.__init__')
class B(Base):
def __init__(self):
super().__init__()
print('B.__init__')
class C(Base):
def __init__(self):
super().__init__()
print('C.__init__')
class D(A, B, C):
def __init__(self):
super(Base,B).__init__(self)
print('D.__init__')
D() #D.__init__
print(D.mro()) #[<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.Base'>, <class 'object'>]
57.tuple([iterable]):是一个不可变的序列类型,具体可参考https://blog.csdn.net/grace666/article/details/98079075
58.class type(object):
class type(name, bases, dict):
传入一个参数时,返回 object 的类型。 返回值是一个 type 对象,通常与 object.__class__ 所返回的对象相同。
推荐使用 isinstance() 内置函数来检测对象的类型,因为它会考虑子类的情况。
传入三个参数时,返回一个新的 type 对象。 这在本质上是 class 语句的一种动态形式。 name 字符串即类名并且会成为 __name__ 属性;bases 元组列出基类并且会成为 __bases__ 属性;而 dict 字典为包含类主体定义的命名空间并且会被复制到一个标准字典成为 __dict__ 属性。
具体可参考:https://blog.csdn.net/grace666/article/details/103446541
59.vars([object]):返回模块、类、实例或任何其它具有 __dict__ 属性的对象的 __dict__ 属性
(1)object为空,vars()==locals()
class A():
def __init__(self,name):
self.name=name
def test(self):
print(self.name)
a=A("hello")
print(vars()) #{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x037CE808>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'A': <class '__main__.A'>}
print(locals()) #{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x037CE808>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'A': <class '__main__.A'>}
(2)当object不为空,参数可以是模块、类、类实例,或者定义了__dict__属性的对象
class A():
def __init__(self,name):
self.name=name
def test(self):
print(self.name)
a=A("hello")
print(vars(A)) #{'__module__': '__main__', '__init__': <function A.__init__ at 0x058901D8>, 'test': <function A.test at 0x05890190>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
print(vars(a)) #{'name': 'hello'}
print(A.__dict__) #{'__module__': '__main__', '__init__': <function A.__init__ at 0x00F201D8>, 'test': <function A.test at 0x00F20190>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
print(a.__dict__) #{'name': 'hello'}
再看一个例子:
class A():
a=1
b=2
def __init__(self):
self.a=3
self.b=4
def test():
return "aaa"
class B(A):
a=5
b=6
def __init__(self):
super().__init__()
# self.a=7
# self.b=8
def test():
return "aaa"
a=A()
b=B()
print(vars(A)) #{'__module__': '__main__', 'a': 1, 'b': 2, '__init__': <function A.__init__ at 0x04FC02B0>, 'test': <function A.test at 0x04FC0268>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
print(vars(B)) #{'__module__': '__main__', 'a': 5, 'b': 6, '__init__': <function B.__init__ at 0x00F50220>, 'test': <function B.test at 0x00F501D8>, '__doc__': None}
print(vars(a)) #{'a': 3, 'b': 4}
print(vars(b)) #{'a': 3, 'b': 4}
由上可见,每个类的类变量、函数名都放在自己的__dict__中;而类实例对象,父类和子类对象的__dict__是公用的
60.zip(*iterables):用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,返回由这些元组组成的对象,其中的第 i 个元组包含来自每个参数序列或可迭代对象的第 i 个元素,这样做可节约了不少内存
(1)参数为空,则返回空迭代器
z=zip()
print(z) #<zip object at 0x000002DCBC2D6048>
print(type(z)) #<class 'zip'>
print(list(z)) #[]
(2)只有1个参数,从iterable中依次取一个元组,组成一个元组
x=[1,2,3]
z=zip(x)
print(list(z)) #[(1,), (2,), (3,)]
注:在python 3.0中有个大坑,zip中的数据只能操作一次,之后内存就会释放
x=[1,2,3]
z=zip(x)
print(list(z)) #[(1,), (2,), (3,)]
print(list(z)) #[]
l1=[[1,2,3],[4,5],[6,7,8]]
z=zip(l1)
print(list(z)) #[([1, 2, 3],), ([4, 5],), ([6, 7, 8],)]
(3)带有2个参数,zip(a,b)zip()函数分别从a和b依次各取出一个元素组成元组,再将依次组成的元组组合成一个新的迭代器
x=[1,2,3]
y=[4,5,6]
z=zip(x, y)
print(z) #<zip object at 0x000002B157D96248>
print(type(z)) #<class 'zip'>
print(list(z)) #[(1, 4), (2, 5), (3, 6)]
print(z) #<zip object at 0x000002B157D96248>
注:当a与b的行数或列数不同时,取两者结构中最小的行数和列数,依照最小的行数和列数将对应位置的元素进行组合
x=[1,2,3,3]
y=[4,5,6,7,8]
z=zip(x, y)
print(list(z)) #[(1, 4), (2, 5), (3, 6), (3, 7)]
(4)使用for循环+列表推导式
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n = [[2, 2, 2], [3, 3, 3], [4, 4, 4]]
print('='*10 + "矩阵点乘" + '='*10) #==========矩阵点乘==========
print([x*y for a, b in zip(m, n) for x, y in zip(a, b)]) #[2, 4, 6, 12, 15, 18, 28, 32, 36]
(5)*zip操作:*zip()函数是zip()函数的逆过程,将zip对象变成原先组合前的数据
a1 = [1,2,3]
a2 = [4,5,6]
a3 = [7,8,9]
a4 = ['a','b','c','d']
z=zip(a1,a2,a3,a4)
print(list(z)) #[(1, 4, 7, 'a'), (2, 5, 8, 'b'), (3, 6, 9, 'c')]
z1=zip(*zip(a1,a2,a3,a4))
print(list(z1)) #[(1, 2, 3), (4, 5, 6), (7, 8, 9), ('a', 'b', 'c')]
本文详细介绍了Python的内置函数,包括abs、all、any、ascii、bin、bool等,涵盖了数值处理、序列检查、类型转换等多个方面。通过这些函数,可以更方便地进行数据操作和程序开发。

938

被折叠的 条评论
为什么被折叠?



