python特性

Python3.8

  • 海象运算符:=
nums = list(range(10))
# 作用:把等号右面表达式的值 赋值给 这个符号 前面的变量
if (length := len(nums)) > 50:
    print(length)
else:
    print(length + 1)
  • fstring增强
name = 'huahua'
age = 18
print(f'{name=}, {age=}')
# name='huahua', age=18
  • 函数增强/*
def fun(a, b, /, c, d, *, e, f):
    print(f'{a=}, {b=}, {c=}, {d=}, {e=}, {f=}')

Python3.9

  • 字典合并
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4, 'b': 5}
new_d = d1 | d2
print(new_d)
# {'a': 1, 'b': 5, 'c': 3, 'd': 4}
  • 字典更新
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4, 'b': 5}
d1 |= d2
print(d1)
# {'a': 1, 'b': 5, 'c': 3, 'd': 4}
  • 字符串方法
s = 'Hello World everyone'
# 删除前缀
s.removeprefix('Hello ')
print(s)
# 删除后缀
s.removesuffix(' everyone')
print(s)

Python3.10

  • match、case
status = 100
match status:
    case 400:
        print('11')
    case 500:
        print('22')
    case _:
        print('default')
  • 新的类型联合运算符
print(isinstance(9, int | str))
# True
  • typing.TypeAlias
from typing import TypeAlias

str_list: TypeAlias = list[str]
L1 = str_list(['1', '2'])
L2 = str_list([1, 2])

#执行静态类型检测器mypy test.py,结果:
#test.py:7: error: List item 0 has incompatible type "int"; expected "str"
#test.py:7: error: List item 1 has incompatible type "int"; expected "str"
#Found 2 errors in 1 file (checked 1 source file)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容