python 3.9 开发计划表
python 官网在2月26日发布了 python3.9.0a4 版本,据官网公布的时间计划表来看,在 python 3.9 开发的过程中,需进行3个版本迭代,分别是 alpha 、beta、和 release(正式版本)。
alpha 和 beta 都是属于测试版本,两者最大的区别是在于: 只要进入 beta阶段就不能再加入新的特性,beta 1标志着正式进入测试、维护阶段
3.9 在 alpha 测试阶段计划要进行6个周期,而目前公布的 python3.9.0a4 是 alpha 6个周期的第4个,距离正式版本的发布还需要有一段时间,根据计划,新版本的正式发布大约会在今年的10月份左右
python3.9 可能加入的新特性
据官网中发布的新版本特性介绍来看,有一个比较大的变化就是 对于字典合并和更新操作,将加入操作符:merge(|) 和update(|=) :
This PEP proposes adding merge (|
) and update (|=
) operators to the built-in dict
class.
目前如果要合并两个字典有下面几种方法,针对每种方法官网指出目前各自存在的缺陷:
1,利用dict.update()
>>> d1 ={'a':1}
>>> d2 = {'b':2}
>>> d1.update(d2)
>>> d1
{'a': 1, 'b': 2}
#else
>>> e =d1.copy()
>>> e.update(d2)
>>> e
{'a': 1, 'b': 2}
>>> d2 = {'b':2}
{'a': 1, 'b': 2}
不足:不是一个表达式,需要增加一个临时变量;
2,{ ** d1,** d2}
>>> d1 ={'a':1}
>>> d2 = {'b':2}
>>> {**d1,**d2}
{'a': 1, 'b': 2}
>>> d2 = {'b':2}
{'a': 1, 'b': 2}
这个方法是在 python3.5 加上去的,官网指出此方法目前存在的缺陷:语法太丑,直观上来看很少人能够猜测是合并字典的意思,,,果然是大 python,这个理由给的我无力反驳
Dict unpacking looks ugly and is not easily discoverable. Few people would be able to guess what it means the first time they see it, or think of it as the "obvious way" to merge two dicts.
3,collections.ChainMap
ChainMap映射方法目前存在的缺陷:1,知名度太小,并且不用户使用不频繁;2,在字典合并之后,如果更改合并之后字典的某个键的值,原来的字典也会受到影响,例如下面的 d1 ;
>>> from collections import ChainMap
>>> d1 ={'a':1}
>>> d2 = {'b':2}
>>> merged = ChainMap(d1,d2)
>>> merged
ChainMap({'a': 1}, {'b': 2})
>>> merged['a'] =3
>>> merged
ChainMap({'a': 3}, {'b': 2})
>>> d1
{'a': 3}
>>> d1 ={'a':1}
{'a': 3}
4, dict(d1,**d2)
此方法不足之处为:此方法不受用户欢迎、合并时必须是 d2 键类型为字符串才能正常运行:
>>> d1 ={'a':1}
>>> d2 = {'b':2}
>>> dict(d1,**d2)
{'a': 1, 'b': 2}
>>> d2 = {5:5}
>>> dict(d1,**d2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: keywords must be strings
>>> d2 = {'b':2}
TypeError: keywords must be strings
新操作符 | 、|= 的使用方法:
即将在版本 3.9 加入操作符 | (这个是官网给的例子)作为字典之间的合并,以后直接输入 a|b 就可以把字典 a 和 b 合并在一起,简单明了。注意的是:如果在字典合并时 a 和 b 之间出现 key 名相同 value 不同情况下,最终的合并结果中出现 key 名相同的值以 b 为准
>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
>>> e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
>>> d | e
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
>>> e | d
{'aardvark': 'Ethel', 'spam': 1, 'eggs': 2, 'cheese': 3}
>>> e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
{'aardvark': 'Ethel', 'spam': 1, 'eggs': 2, 'cheese': 3}
2,操作符 |=是 |的拓展版都可用于字典合并、更新, |= 一个显著特性是在 在合并时,a 和 b 不一定需要都是字典类型,只要是键值对形式,语法自动进行类型修正并进行合并(例子如下)
>>> d | [('spam', 999)]
Traceback (most recent call last):
TypeError: can only merge dict (not "list") to dict
>>> d |= [('spam', 999)]
>>> d
{'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel', 'spam': 999}
Traceback (most recent call last):
{'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel', 'spam': 999}
以上就是 python官网在 3.9版本中对于字典新特性 的一些介绍,关于版本的更新会继续跟进。最后,感谢大家的阅读!
扫描上方二维码即可关注