https://github.com/ltoddy/Python-useful
Do you want to be a Python expert ?
很多時(shí)候,有些人在介紹 Python
的時(shí)候會(huì)提到 The Zen of Python
:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
但是我不知道你需要多久才能做到 The Zen of Python
中說(shuō)的.
Python
真的優(yōu)雅嗎, Python
真的簡(jiǎn)潔嗎, 這是當(dāng)然, 不然 The Zen of Python
怎么會(huì)添加到標(biāo)準(zhǔn)庫(kù)中去.
不過(guò)在此之前,你需要更加的學(xué)習(xí)(畢竟不是一上來(lái)就什么都會(huì)的), 明白 Python 的風(fēng)格, 或者說(shuō)需要自己不斷鍛煉, 讓自己寫出來(lái)的 Python 代碼更加的 pythonic.
在這里, 我不會(huì)講述類似:
a, b = b, a
l = [x * 2 for x in range(10)]
類似這種你本就應(yīng)該在初學(xué) Python
就應(yīng)該熟練掌握的東西.
我更想講述的是:
data model class (dunder methods, protocol).
metaclass (Base/Derive class)
Decorators
Generators
Context Managers
因?yàn)橐陨系囊恍ゝeature確實(shí)可以讓你的代碼更加pythonic
, 而且也是非常重要的.
A problem
在很早很早之前,曾經(jīng)看到一個(gè)群友問(wèn)了一個(gè)問(wèn)題:
有兩個(gè)list, 比如: one = [1, 2, 3], other = [2, 3, 4]
他想要得到這樣的結(jié)果,把這兩個(gè)相加得到: [3, 5, 7], 也就是對(duì)應(yīng)下標(biāo)的元素相加.
我當(dāng)時(shí)想都沒(méi)想就回了一句: return [one[i] + other[i] for i in range(len())]
看上去不錯(cuò),是嗎?
當(dāng)然不是. 如果這兩個(gè)list不相等怎么辦?
然后我又給了一個(gè)方案: return list(map(lambda x, y: x + y, one, other))
不過(guò), 這樣又不好了, 如果一個(gè)list長(zhǎng),一個(gè)list短,這個(gè)樣子寫,長(zhǎng)的那個(gè)list多出來(lái)的數(shù)據(jù)就會(huì)被丟掉了.
所以我又思考了一下, 重新給出了最后結(jié)果: return list(starmap(lambda x, y: x + y, zip_longest(one, ther, fillvalue=0)))
你能想到我所說(shuō)的最后一種方案嗎?
What is Python ?
Python 到底是一種什么樣的語(yǔ)言, 說(shuō)真的, 很難給 Python 下一個(gè)定義,因?yàn)樗姆妒綄?shí)在太多:
面向?qū)ο?/p>
過(guò)程式
面向協(xié)議
原型
也支持函數(shù)式的feature
Python is an interpreted, interactive, object-oriented programming language. (來(lái)自Python docs)
如果你真正理解這些 feature 是什么, 那么非常顯然的是, 來(lái)告訴我: why and when you use it. (畢竟我更傾向于實(shí)用, 我不是學(xué)院派)
當(dāng)然,在最后的時(shí)候,我也會(huì)告訴一些學(xué)習(xí)途徑, 比如看什么書可以最快的提高你的能力, 也比如你應(yīng)該從哪些地方去獲取你需要掌握的知識(shí).