Python 3.5 帶給我們的方便的矩陣以及其他改進(jìn)
Python 3.5 在 2015 年首次發(fā)布,盡管它已經(jīng)發(fā)布了很長時間,但它引入的許多特性都沒有被充分利用,而且相當(dāng)酷。下面是其中的三個。
@ 操作符
@ 操作符在 Python 中是獨(dú)一無二的,因?yàn)樵跇?biāo)準(zhǔn)庫中沒有任何對象可以實(shí)現(xiàn)它!它是為了在有矩陣的數(shù)學(xué)包中使用而添加的。
矩陣有兩個乘法的概念。元素積是用 * 運(yùn)算符完成的。但是矩陣組合(也被認(rèn)為是乘法)需要自己的符號。它是用 @ 完成的。
例如,將一個“八轉(zhuǎn)”矩陣(將軸旋轉(zhuǎn) 45 度)與自身合成,就會產(chǎn)生一個四轉(zhuǎn)矩陣。
- import numpy
- hrt2 = 2**0.5 / 2
- eighth_turn = numpy.array([
- [hrt2, hrt2],
- [-hrt2, hrt2]
- ])
- eighth_turn @ eighth_turn
- array([[ 4.26642159e-17, 1.00000000e+00],
- [-1.00000000e+00, -4.26642159e-17]])
浮點(diǎn)數(shù)是不精確的,這比較難以看出。從結(jié)果中減去四轉(zhuǎn)矩陣,將其平方相加,然后取其平方根,這樣就比較容易檢查。
這是新運(yùn)算符的一個優(yōu)點(diǎn):特別是在復(fù)雜的公式中,代碼看起來更像基礎(chǔ)數(shù)學(xué):
- almost_zero = ((eighth_turn @ eighth_turn) - numpy.array([[0, 1], [-1, 0]]))**2
- round(numpy.sum(almost_zero) ** 0.5, 10)
- 0.0
參數(shù)中的多個關(guān)鍵詞字典
Python 3.5 使得調(diào)用具有多個關(guān)鍵字-參數(shù)字典的函數(shù)成為可能。這意味著多個默認(rèn)值的源可以與更清晰的代碼”互操作“。
例如,這里有個可笑的關(guān)鍵字參數(shù)的函數(shù):
- def show_status(
- *,
- the_good=None,
- the_bad=None,
- the_ugly=None,
- fistful=None,
- dollars=None,
- more=None
- ):
- if the_good:
- print("Good", the_good)
- if the_bad:
- print("Bad", the_bad)
- if the_ugly:
- print("Ugly", the_ugly)
- if fistful:
- print("Fist", fistful)
- if dollars:
- print("Dollars", dollars)
- if more:
- print("More", more)
當(dāng)你在應(yīng)用中調(diào)用這個函數(shù)時,有些參數(shù)是硬編碼的:
- defaults = dict(
- the_good="You dig",
- the_bad="I have to have respect",
- the_ugly="Shoot, don't talk",
- )
從配置文件中讀取更多參數(shù):
- import json
- others = json.loads("""
- {
- "fistful": "Get three coffins ready",
- "dollars": "Remember me?",
- "more": "It's a small world"
- }
- """)
你可以從兩個源一起調(diào)用這個函數(shù),而不必構(gòu)建一個中間字典:
- show_status(**defaults, **others)
- Good You dig
- Bad I have to have respect
- Ugly Shoot, don't talk
- Fist Get three coffins ready
- Dollars Remember me?
- More It's a small world
os.scandir
os.scandir 函數(shù)是一種新的方法來遍歷目錄內(nèi)容。它返回一個生成器,產(chǎn)生關(guān)于每個對象的豐富數(shù)據(jù)。例如,這里有一種打印目錄清單的方法,在目錄的末尾跟著 /:
- for entry in os.scandir(".git"):
- print(entry.name + ("/" if entry.is_dir() else ""))
- refs/
- HEAD
- logs/
- index
- branches/
- config
- objects/
- description
- COMMIT_EDITMSG
- info/
- hooks/
歡迎來到 2015 年
Python 3.5 在六年前就已經(jīng)發(fā)布了,但是在這個版本中首次出現(xiàn)的一些特性非???,而且沒有得到充分利用。如果你還沒使用,那么將他們添加到你的工具箱中。