当前位置: 首页 > 科技观察

Python3.9,我们来了!

时间:2023-03-14 18:22:23 科技观察

Python3.9,我们来了!在过去的一年里,来自世界各地的开发人员一直致力于改进Python3.8。Python3.9beta版本已经发布了一段时间,首次正式发布于2020年10月5日。每个Python版本都包含新的开发和改进,Python3.9也不例外。下面介绍Python3.9的几大新特性。1.Dictionary(merge&update)运算符Dictionary是Python中最基本的数据结构之一,其性能随着python版本的迭代不断优化。在Python3.9中,合并(|)和更新(|=)运算符已添加到dict类中。这些更新补充了现有的dict.update和{**d1,**d2}方法。传统的字典合并方法:>>>pycon={2016:"Portland",2018:"Cleveland"}#dictionary1>>>europython={2017:"Rimini",2018:"Edinburgh",2019:"Basel"}#dictionary2#方法一>>>{**pycon,**europython}{2016:'波特兰',2018:'爱丁堡',2017:'里米尼',2019:'巴塞尔'}#方法二>>>merged=pycon.copy()>>>forkey,valueineuropython.items():...merged[key]=value...>>>merged{2016:'波特兰',2018:'爱丁堡',2017:'Rimini',2019:'Basel'}这两种方法都在不改变原始数据的情况下合并了字典。请注意,字典1中的“Cleveland”已被合并字典2中的“Edinburgh”覆盖。您还可以更新字典1:>>>pycon.update(europython)>>>pycon{2016:'Portland',2018:'Edinburgh',2017:'Rimini',2019:'Basel'}引入了新版本的Python添加了两个新的字典运算符:合并(|)和更新(|=)。你可以使用|合并两个词典和|=更新一个词典:>>>pycon={2016:"Portland",2018:"Cleveland"}>>>europython={2017:"Rimini",2018:"Edinburgh",2019:“巴塞尔”}>>>pycon|europython#merge{2016:'波特兰',2018:'爱丁堡',2017:'里米尼',2019:'巴塞尔'}>>>pycon|=europython#更新>>>pycon{2016:'Portland',2018:'Edinburgh',2017:'Rimini',2019:'Basel'}d1|d2与{**d1,**d2}类似,都用于合并字典取union,当遇到相同的key时,后者会覆盖前者。使用|的优点之一是它适用于类似字典的类型并在合并后保留原始类型:>>>fromcollectionsimportdefaultdict>>>europe=defaultdict(lambda:"",{"Norway":"Oslo","Spain":"Madrid"})>>>africa=defaultdict(lambda:"",{"Egypt":"Cairo","Zimbabwe":"Harare"})>>>europe|africadefaultdict(at0x7f0cb42a6700>,{'挪威':'奥斯陆','西班牙':'马德里','埃及':'开罗','津巴布韦':'哈拉雷'})>>>{**欧洲,**非洲}{'挪威':'奥斯陆','Spain':'Madrid','Egypt':'Cairo','Zimbabwe':'Harare'}|=是更新字典,类似于.update():>>>libraries={..."collections":"Containerdatatypes",..."math":"Mathematicalfunctions",...}>>>libraries|={"zoneinfo":"IANAtimezonesupport"}>>>libraries{'collections':'Containerdatatypes','math':'Mathematicalfunctions','zoneinfo':'IANAtimezonesupport'}|=你也可以使用类似的词典更新的数据结构:>>>libraries|=[("graphlib","Functionalityforgraph-likestructures")]>>>libraries{'collections':'Containerdatatypes','math':'Mathematicalfunctions','zoneinfo':'IANAtimezonesupport','graphlib':'Functionalityforgraph-likestructures'}2.去除字符串前缀和后缀在Python3.9中,您可以使用.removeprefix()和.removesuffix()去除字符串的开头或结尾分别为:>>>"threecoolfeaturesinPython".removesuffix("Python")'threecoolfeaturesin'>>>"threecoolfeaturesinPython".removeprefix("three")'coolfeaturesinPython'>>>"threecoolfeaturesinPython".removeprefix("Somethingelse")'threecoolfeaturesinPython'有人会说。strip方法也是可以的,但是这种方法会造成误删:>>>"threecoolfeaturesinPython".strip("Python")'reecoolfeaturesi'可以看到明明是要删掉最后的python字样,但是那里的开头也删除了-Th的删除部分,所以.removeprefix()和.removesuffix()可能更精确。3.zoneinfo时区模块zoneinfo是python3.9引入的新模块,zoneinfo可以访问InternetAssignedNumbersAuthority(IANA)时区数据库。IANA每年更新数次数据库,是最权威的时区信息来源。使用zoneinfo,您可以获取描述数据库中任何时区的对象:>>>fromzoneinfoimportZoneInfo>>>ZoneInfo("America/Vancouver")zoneinfo.ZoneInfo(key='America/Vancouver')>>>fromzoneinfoimportZoneInfo>>>fromdatetimeimportdatetime,timedelta>>>#Daylightsavingtime>>>dt=datetime(2020,10,31,12,tzinfo=ZoneInfo("America/Los_Angeles"))>>>print(dt)2020-10-3112:00:00-07:00>>>dt.tzname()'PDT'>>>#standardtime>>>dt+=timedelta(days=7)>>>print(dt)2020-11-0712:00:00-08:00>>>打印(dt.tzname())PST4。用于类型提示的内置集合类型在类型提示中,您现在可以将内置集合类型(例如list和dict)用作泛型类型,而无需从输入中导入相应的大写类型(例如List或Dict).defgreet_all(names:list[str])->None:fornameinnames:print("Hello",name)5.拓扑排序Python3.9新增了一个模块graphlib,其中包含graphlib.TopologicalSorter类,提供拓扑排序功能。>>>dependencies={..."realpython-reader":{"feedparser","html2text"},..."feedparser":{"sgmllib3k"},...}...>>>fromgraphlibimportTopologicalSorter>>>ts=TopologicalSorter(dependencies)>>>list(ts.static_order())['html2text','sgmllib3k','feedparser','realpython-reader']6.最小公倍数(LCM)Python长had计算两个数的最大公约数(GCD)的函数:>>>importmath>>>math.gcd(49,14)7最小公倍数(LCM)与最大公约数(GCD)有关,可以根据GCDLCM定义:>>>deflcm(num1,num2):...ifnum1==num2==0:...return0...returnnum1*num2//math.gcd(num1,num2)。..>>>lcm(49,14)98在Python3.9中,不再需要定义自己的LCM函数,增加了计算最小公倍数的函数:>>>importmath>>>math.lcm(49,14)987。更强大的Python解析器Python3.9最酷的功能之一是您在日常编程中没有注意到的最酷的功能之一是解析器的更新。解析器是Python解释器的基本组件。在最新版本中,解析器已经重建。Python历来使用LL(1)解析器将源代码解析为解析树。您可以将LL(1)解析器视为一次读取一个字符并在不回溯的情况下解释源代码的解析器。新的解释器是基于PEG(解析表达式语法)实现的,而不是LL(1)。新解析器的性能与旧解析器相当,PEG在设计新语言特性时比LL(1)更灵活。在整个标准库中,PEG解析器稍快一些,但也使用更多内存。事实上,在使用新的解析器时很难察觉性能的提高或降低。