建議你去看一本書:《計算機程序的構造與解釋》。里面用的語言是Scheme,一種Lisp的方言。通過這本書學習程序的抽象、封裝,以及重要的函數(shù)式編程思想。等看完這本書以后,你在來寫寫Python代碼,就知道如何讓其簡潔直觀而又不失其可讀性了。
創(chuàng)新互聯(lián)公司2013年開創(chuàng)至今,是專業(yè)互聯(lián)網(wǎng)技術服務公司,擁有項目成都網(wǎng)站制作、成都網(wǎng)站建設網(wǎng)站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元膠州做網(wǎng)站,已為上家服務,為膠州各地企業(yè)和個人服務,聯(lián)系電話:18980820575
同時,要讓代碼寫得簡潔,你也得熟悉Python本身,充分挖掘其能力。Python內(nèi)建的幾個高階函數(shù):map,reduce,filter,enumerate等等,lambda表達式,zip函數(shù),以及標準庫里強大的itertools、functools模塊,都是函數(shù)式編程的利器。此外Python本身提供了許多非常好的語法糖衣,例如裝飾器、生成器、*args和**kwargs參數(shù)、列表推導等等,也是簡化代碼的有效手段。還有,Python有著強大的庫。多參考官方的文檔了解其原理和細節(jié),我相信你也能寫出高效簡潔的代碼的。
其實代碼的簡潔沒有什么捷徑,它要求你了解你要解決的問題,所使用的語言和工具,相關的算法或流程。這些都得靠你自己不斷地練習和持續(xù)改進代碼,不斷地專研問題和學習知識。加油吧,少年!
樓下讓你參考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!
'''
讓我們來做個小游戲吧:統(tǒng)計上面這段話的單詞總數(shù)目,以及各個單詞的數(shù)量(不區(qū)分大小寫),然后按字典順序輸出每個單詞出現(xiàn)的次數(shù)。要求,例如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
#!bin/python #-*- encoding: utf-8 -*- def counter(path, find, punctuation): infile = open(path, "r") lenth = len(find) count = [] for i in range(lenth): count.append(0) dat = infile.readline().strip("\n") while dat != '': dat = dat.split() for elemt in dat: elemt = elemt.strip(punctuation) #去除標點符號 if elemt in find: i = find.index(elemt) count[i] += 1 dat = infile.readline().strip("\n") infile.close() for i in range(lenth): print "%s:%d次" % (find[i],count[i]) if __name__ == "__main__": path = "PATH" find = ["hello", "hi", "world"] punctuation = ''',.;'":!?''' counter(path, find, punctuation)
python讀取段落需要自定義函數(shù):
from _ _future_ _ import generators
def paragraphs(fileobj, separator='\n'):
if separator[-1:] != '\n': separator += '\n' paragraph = []
for line in fileobj:
if line == separator:
if paragraph: yield ''.join(paragraph)
paragraph = []
else: paragraph.append(line)
if paragraph: yield ''.join(paragraph)
python最基本的要求就是縮進. 每個段落都有不同的縮進,所以會形成不一樣的流程控制. 你這樣 直接一行的話. 至少我看不懂. 如果你提問的時候不想被頁面的縮進影響. 那你提問的時候 ,應該可以考慮, 在notepad++里面寫好.貼個圖上來.
Python是通過縮進來進行代碼布局的??梢栽O置幾個空格來代表一個tab,從而來布局Python函數(shù)的縮進。注釋必須跟代碼保持一致,當你想修改代碼時,建議優(yōu)點修改注釋。 注釋必須是完整的句子。 如果注釋是一個句子或者短語,請首字母大寫。 如果注釋很短,建議省略句末的句號。 注釋塊通常由一個或者多個由完整句子構成的段落組成,每個句子應該以句號結尾。 注釋請使用英文。 約定使用統(tǒng)一的文檔化注釋格式有助于良好的習慣和團隊的進步。