Python 3.10的幾個好用的新特性

來源:Deephub Imba 本文約1200字,建議閱讀5分鐘?
本文為你介紹Python 3.10新的有用的特性。?
更詳細(xì)語法錯誤提示信息

結(jié)構(gòu)模式匹配
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 1Number is 2Number is 3Number 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.Randomval x: Int = Random.nextInt(10)x match {case 0 => "zero"case 1 => "one"case 2 => "two"case _ => "other"}
新型聯(lián)合運算符
def square(number: int|float):return number ** 2
square(2.5)6.25
isinstance("3",int|str)Trueisinstance("GoodBye",int|str)True
現(xiàn)有模塊的一些改進(jìn)
>>> pprint.pformat(int(1e9),underscore_numbers=True)'1_000_000_000'
value = 50print(bin(value))0b101010print(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
總結(jié)
評論
圖片
表情
