展開全部
python代碼大全可復制免費。建2113議你去看一本書:《計算機程序5261的構造與解釋》。里面4102用的語言是Scheme,一種Lisp的方言。通1653過這本書學習程序的抽象、封裝,以及重要的函數式編程思想。等看完這本書以后,你在來寫寫Python代碼,就知道如何讓其簡潔直觀而又不失其可讀性了。
同時,要讓代碼寫得簡潔,你也得熟悉Python本身,充分挖掘其能力。Python內建的幾個高階函數:map,reduce,filter,enumerate等等,lambda表達式,zip函數,以及標準庫里強大的itertools、functools模塊,都是函數式編程的利器。此外Python本身提供了許多非常好的語法糖衣,例如裝飾器、生成器、*args和**kwargs參數、列表推導等等,也是簡化代碼的有效手段。還有,Python有著強大的庫。多參考官方的文檔了解其原理和細節,我相信你也能寫出高效簡潔的代碼的。
python編寫一個簡單的程序,其實代碼的簡潔沒有什么捷徑,它要求你了解你要解決的問題,所使用的語言和工具,相關的算法或流程。這些都得靠你自己不斷地練習和持續改進代碼,不斷地專研問題和學習知識。加油吧,少年!
樓下讓你參考PEP 20,其實不用去查,標準庫里的this模塊就是它(試試import this):The Zen of Python(Python之禪)。它就是一段話:s='''
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!
'''
讓我們來做個小游戲吧:統計上面這段話的單詞總數目,以及各個單詞的數量(不區分大小寫),然后按字典順序輸出每個單詞出現的次數。要求,例如it's和you're等要拆分成it is和you are。你會怎么寫代碼呢?如何保持簡潔呢?
下面是我的參考答案,爭取比我寫的更簡潔吧~import re
p = re.compile("(\w+)('s|'re|n't)?")
wc = {}
tail_map = { "'s" : 'is', "'re" : 'are', "n't": 'not'}
for m in re.finditer(p, s):
word = m.group(1).lower() # Get the word in lower case
wc[word] = wc.get(word, 0) + 1 # Increase word count
tail = m.group(2) # Get the word tail
if tail is not None: # If a word tail exists,
tail = tail_map[tail] # map it to its full form
wc[tail] = wc.get(tail, 0)+1 # Increase word count
print ('Total word count: %d'%sum(wc.values())) # Output the total count
max_len = max(map(len, wc.keys())) # Calculate the max length of words for pretty printing
for w in sorted(wc.keys()): # Sort the words
print ('%*s => %d'%(max_len, w, wc[w])) # Output
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态