15个最近才知道的Python实用操作

张开发
2026/4/21 23:53:37 15 分钟阅读

分享文章

15个最近才知道的Python实用操作
1映射代理不可变字典映射代理是创建后无法更改的字典。如果我们不希望用户能够更改我们的值就可以使用它。123456fromtypesimportMappingProxyTypempMappingProxyType({apple:4,orange:5})print(mp)# {apple: 4, orange: 5}如果我们尝试更改映射代理中的内容就会出现错误。123456789101112fromtypesimportMappingProxyTypempMappingProxyType({apple:4,orange:5})print(mp)Traceback (most recent call last):File some/path/a.py, line 4, in modulemp[apple] 10~~^^^^^^^^^TypeError: mappingproxy object does not support item assignment2) dict 对于类和对象是不同的1234567891011121314151617classDog:def__init__(self, name, age):self.namenameself.ageagerockyDog(rocky,5)print(type(rocky.__dict__))# class dictprint(rocky.__dict__)# {name: rocky, age: 5}print(type(Dog.__dict__))# class mappingproxyprint(Dog.__dict__)# {__module__: __main__,# __init__: function Dog.__init__ at 0x108f587c0,# __dict__: attribute __dict__ of Dog objects,# __weakref__: attribute __weakref__ of Dog objects,# __doc__: None}对象的 dict 属性是普通字典而类的 dict 属性是映射代理它们本质上是不可变字典无法更改。3) any() 和 all()1234567any([True,False,False])# Trueany([False,False,False])# Falseall([True,False,False])# Falseall([True,True,True])# Trueany() 和 all() 函数都接受可迭代对象例如列表。any() 如果至少有一个元素为 True则返回 True。all() 只有当所有元素都为 True 时才返回 True。4) divmod()内置的divmod()函数可以同时执行//和%运算符。1234quotient, remainderdivmod(27,10)print(quotient)# 2print(remainder)# 7这里27 // 10 的值为2而 27 % 10 的值为7。因此返回元组2,7。5) 使用格式化字符串轻松检查变量1234567namerockyage5stringf{name} {age}print(string)# namerocky age5在格式化字符串中我们可以在变量后面添加 以使用 var_namevar_value 的语法打印它。6) 我们可以将浮点数转换为比率12345print(float.as_integer_ratio(0.5))# (1, 2)print(float.as_integer_ratio(0.25))# (1, 4)print(float.as_integer_ratio(1.5))# (3, 2)内置的 float.as_integer_ratio() 函数允许我们将浮点数转换为表示分数的元组。但有时它会表现得很奇怪。123print(float.as_integer_ratio(0.1))# (3602879701896397, 36028797018963968)print(float.as_integer_ratio(0.2))# (3602879701896397, 18014398509481984)7) 用globals()和locals()显示现有的全局/本地变量1234x1print(globals())# {__name__: __main__, __doc__: None, ..., x: 1}内置的 globals() 函数返回一个包含所有全局变量及其值的字典。12345678deftest():x1y2print(locals())test()# {x: 1, y: 2}内置函数 locals() 返回一个包含所有局部变量及其值的字典。8) import() 函数12importnumpy as npimportpandas as pd^ 导入模块的常规方式。12np__import__(numpy)pd__import__(pandas)^ 这与上面的代码块执行相同的操作。9) Python中的无限值12afloat(inf)bfloat(-inf)^ 我们可以定义正无穷和负无穷。 正无穷大于所有其他数字而负无穷小于所有其他数字。10) 我们可以使用 ‘pprint’ 来漂亮地打印东西1234567frompprintimportpprintd{A:{apple:1,orange:2,pear:3},B:{apple:4,orange:5,pear:6},C:{apple:7,orange:8,pear:9}}pprint(d)11) 我们可以在Python中打印彩色输出我们需要先安装colorama。12345fromcoloramaimportForeprint(Fore.REDhello world)print(Fore.BLUEhello world)print(Fore.GREENhello world)12) 创建字典的更快方法1d1{apple:pie,orange:juice,pear:cake}^ 正常的方式1d2dict(applepie, orangejuice, pearcake)^更快的方法。这与上面的代码块完全相同但我们输入较少的引号。

更多文章