Python 3.10的几个好用的新特性
来源:Deephub Imba 本文约1200字,建议阅读5分钟
本文为你介绍Python 3.10新的有用的特性。
更详细语法错误提示信息
结构模式匹配
numbers = [1,2,3,4]
for n in numbers:
match n:
case 1:
print("Number is 1")
case 2:
print("Number is 2")
case 3:
print("Number is 3")
case _:
print("Number is not 1,2 or 3")
Number is 1
Number is 2
Number is 3
Number is not 1,2 or 3
def human_age(person): # person = (name, age, gender)
match person:
case (name, _, "male"):
print(f"{name} is man.")
case (name, _, "female"):
print(f"{name} is woman.")
case (name, age, gender):
print(f"{name} is {age} old.")
human_age(("Carol", 25, "female"))
Carol is woman.
import scala.util.Random
val x: Int = Random.nextInt(10)
x match {
case 0 => "zero"
case 1 => "one"
case 2 => "two"
case _ => "other"
}
新型联合运算符
def square(number: int|float):
return number ** 2
square(2.5)
6.25
isinstance("3",int|str)
Trueisinstance("GoodBye",int|str)
True
现有模块的一些改进
>>> pprint.pformat(int(1e9),underscore_numbers=True)
'1_000_000_000'
value = 50
print(bin(value))
0b101010
print(value.bit_count())
3
>>> import statistics
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> statistics.covariance(x,y)
0.75
>>> years = [2001,2005,2010]
>>> houses_built = [5,8,14]
>>> slope, intercept = statistics.linear_regression(years, houses_built)
>>> round(slope * 2017 + intercept)
21
总结
评论