摘要:代碼改為根據(jù)數(shù)據(jù)結(jié)構(gòu),第一個(gè)數(shù)據(jù)是名字,第二個(gè)是生日,第二個(gè)之后是成績,所以分別將相關(guān)數(shù)據(jù)賦值到字典里面。是否知道何時(shí)使用列表而何時(shí)使用字典,這正式從好的程序員中區(qū)分出優(yōu)秀程序員的一個(gè)標(biāo)準(zhǔn)。特定函數(shù)應(yīng)用特定數(shù)據(jù)。更加正規(guī)的做法是建立類。
樣例數(shù)據(jù)
Sarah Sweeney,2002-6-17,2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22需要將數(shù)據(jù)整理,實(shí)現(xiàn)人名+出生日期+成績的輸出 以往的做法是:
def sanitize(time_string): if "-" in time_string: splitter = "-" elif ":" in time_string: splitter = ":" else: return(time_string) (mins, secs) = time_string.split(splitter) return(mins + "." + secs) def get_coach_data(filename): try: with open(filename) as f: data = f.readline() return(data.strip().split(",")) except IOError as ioerr: print("File error: " + str(ioerr)) return(None) sarah = get_coach_data("sarah2.txt") (sarah_name, sarah_dob) = sarah.pop(0), sarah.pop(0) print(sarah_name + ""s fastest times are: " + str(sorted(set([sanitize(t) for t in sarah]))[0:3]))這次加入了字典的做法
字典將數(shù)據(jù)值與鍵關(guān)聯(lián):
key --> value Name "sarah sweeney" DOB "2002-6-17" Times "[2:58,2.58,2:39,2-25,2-55,2:54,2.18,2:55,2:55,2:22,2-21,2.22]"
創(chuàng)建字典的方式可以是
cleese = {} #大括號(hào)??!
也可以是
palin = dict()
關(guān)聯(lián)key和value的話是
cleese["Name"] = "John Cleese" # 一個(gè)key 對(duì)應(yīng)一個(gè)字符串
或者
cleese["Name"] = ["John Cleese","John Cleese1","John Cleese2","John Cleese3","John Cleese4"] #一個(gè)key對(duì)應(yīng)一個(gè)list
或者
cleese = {"Name":"abc","Address":"asdasdasda"} #注意是用冒號(hào)
另外數(shù)據(jù)值與key關(guān)聯(lián)后,需要訪問數(shù)據(jù)值里面的某個(gè)數(shù)據(jù)項(xiàng)的話,可以是
cleese["Name"][-1]
類似多維數(shù)組使用。
代碼改為
#!/usr/bin/python # -*- coding: utf-8 -*- def sanitize(time_string): if "-" in time_string: splitter = "-" elif ":" in time_string: splitter = ":" else: return(time_string) (mins,secs) = time_string.split(splitter) return (mins + "." + secs) def get_coach_data(filename): try: with open(filename) as f: data = f.readline() return(data.strip().split(",")) except IOError as ioerr: print("File error:" + str(ioerr)) return(None) sarah = get_coach_data("sarah2.txt") sarah_data={} sarah_data["Name"] = sarah.pop(0) #根據(jù)數(shù)據(jù)結(jié)構(gòu),第一個(gè)數(shù)據(jù)是名字,第二個(gè)是生日,第二個(gè)之后是成績,所以分別將相關(guān)數(shù)據(jù)賦值到字典里面。 sarah_data["DOB"] = sarah.pop(0) sarah_data["Times"] = sarah print(sarah_data["Name"] + ""s fastest times are: " + str(sorted(set([sanitize(t) for t in sarah_data["Times"]]))[0:3]))
為了更加方便的處理多個(gè)人的成績的數(shù)據(jù),所以將字典數(shù)據(jù)轉(zhuǎn)移到函數(shù)里面去,直接通過函數(shù)生成出字典,并返回需要的數(shù)據(jù)字典的方法優(yōu)勢在于合理使用數(shù)據(jù)結(jié)構(gòu)。是否知道何時(shí)使用列表而何時(shí)使用字典,這正式從好的程序員中區(qū)分出優(yōu)秀程序員的一個(gè)標(biāo)準(zhǔn)。
字典其實(shí)也叫“映射”,“散列”,“關(guān)聯(lián)數(shù)組”
#!/usr/bin/python # -*- coding: utf-8 -*- def sanitize(time_string): if "-" in time_string: splitter = "-" elif ":" in time_string: splitter = ":" else: return(time_string) (mins,secs) = time_string.split(splitter) return (mins + "." + secs) def get_coach_data(filename): try: with open(filename) as f: data = f.readline() templ = data.strip().split(",") return({"Name":templ.pop(0), #這里就是字典 "DOB":templ.pop(0), "Times":str(sorted(set([sanitize(t) for t in templ]))[0:3])}) except IOError as ioerr: print("File error:" + str(ioerr)) return(None) sarah = get_coach_data("sarah2.txt") james = get_coach_data("james2.txt") print(sarah["Name"] + ""s fastest times are: " + sarah["Times"])
這就是將代碼和數(shù)據(jù)打包在一起。特定函數(shù)應(yīng)用特定數(shù)據(jù)。
更加正規(guī)的做法是建立類。類是面向?qū)ο髈op編程模型的東西,類的概念在這里不詳細(xì)描述。
類可以
1.降低復(fù)雜性 2.方便維護(hù)和擴(kuò)展
python的類需要有一個(gè)self參數(shù),這個(gè)參數(shù)是用來標(biāo)識(shí)是屬于哪個(gè)對(duì)象實(shí)例的
例如:
class Athlete: def __init__(self,value=0): self.thing = value #定義這個(gè)類的屬性thing def how_big(self) #定義一個(gè)方法how_big return(len(self.thing))
btw:init 是類的python固定實(shí)現(xiàn)方法,所以是必須的。
你寫的代碼 --> python執(zhí)行的代碼 d = Athlete("Holy Grail") Athlete.__init__(d,"Holy Grail") | | | 類 方法 目標(biāo)標(biāo)識(shí)符 | | | d.how_big() Athlete.how_big(d)
代碼改為:
def sanitize(time_string): if "-" in time_string: splitter = "-" elif ":" in time_string: splitter = ":" else: return(time_string) (mins, secs) = time_string.split(splitter) return(mins + "." + secs) class Athlete: def __init__(self, a_name, a_dob=None, a_times=[]): self.name = a_name #通過類的屬性來定義name,dob和times self.dob = a_dob self.times = a_times def top3(self): return(sorted(set([sanitize(t) for t in self.times]))[0:3]) def get_coach_data(filename): try: with open(filename) as f: data = f.readline() templ = data.strip().split(",") return(Athlete(templ.pop(0), templ.pop(0), templ)) except IOError as ioerr: print("File error: " + str(ioerr)) return(None) james = get_coach_data("james2.txt") julie = get_coach_data("julie2.txt") mikey = get_coach_data("mikey2.txt") sarah = get_coach_data("sarah2.txt") print(james.name + ""s fastest times are: " + str(james.top3())) print(julie.name + ""s fastest times are: " + str(julie.top3())) print(mikey.name + ""s fastest times are: " + str(mikey.top3())) print(sarah.name + ""s fastest times are: " + str(sarah.top3()))
在類里面增加一個(gè)靈活的增加成績數(shù)據(jù)的函數(shù)科普:
1.通過在各個(gè)對(duì)象的屬性中保留原始數(shù)據(jù),可以支持類擴(kuò)展來滿足將來的其他需求。如果處理數(shù)據(jù)并作為對(duì)象初始化代碼的一部分,說明你已對(duì)程序員將如何使用這個(gè)類做出了假設(shè),而日后這些假設(shè)肯定會(huì)對(duì)你造成障礙。
可以是增加單個(gè)成績,或是增加多個(gè)成績
單個(gè)成績用add_time,傳入的是字符串
多個(gè)成績是add_times,傳入的是list
以下是單個(gè)成績的樣例:
#!/usr/bin/python # -*- coding: utf-8 -*- class Athlete: def __init__(self,a_name,a_dob=None,a_times=[]): self.name = a_name self.dob = a_dob self.times = a_times def add_time(self,time_value): #這里就是了。 self.times.append(time_value) def top3(self): return (sorted(set([sanitize(t) for t in self.times]))[0:15]) def add_times(self,list_of_times): self.times.extend(list_of_times) def sanitize(time_string): if "-" in time_string: splitter = "-" elif ":" in time_string: splitter = ":" else: return(time_string) (mins,secs) = time_string.split(splitter) return (mins + "." + secs) def get_coach_data(filename): try: with open(filename) as f: data = f.readline() templ = data.strip().split(",") return (Athlete(templ.pop(0),templ.pop(0),templ)) except IOError as ioerr: print("File error:" + str(ioerr)) return(None) sarah = get_coach_data("sarah2.txt") sarah.add_time("2.88") #這里調(diào)用 print(sarah.name + ""s fastest times are: " + str(sarah.top3())) #輸出結(jié)果會(huì)改變觀察到這個(gè)類有點(diǎn)像list,所以有重復(fù)制造車輪的嫌疑,并且功能單一,所以決定集成list類
def sanitize(time_string): if "-" in time_string: splitter = "-" elif ":" in time_string: splitter = ":" else: return(time_string) (mins, secs) = time_string.split(splitter) return(mins + "." + secs) class AthleteList(list): #繼續(xù)list類,所以這里要寫list的名字 def __init__(self, a_name, a_dob=None, a_times=[]): list.__init__([]) #這里需要初始化list類 self.name = a_name self.dob = a_dob self.extend(a_times) #因?yàn)榧蒷ist類了,所以這里可以直接使用list的extend方法 def top3(self): return(sorted(set([sanitize(t) for t in self]))[0:3]) def get_coach_data(filename): try: with open(filename) as f: data = f.readline() templ = data.strip().split(",") return(AthleteList(templ.pop(0), templ.pop(0), templ)) except IOError as ioerr: print("File error: " + str(ioerr)) return(None) james = get_coach_data("james2.txt") julie = get_coach_data("julie2.txt") mikey = get_coach_data("mikey2.txt") sarah = get_coach_data("sarah2.txt") print(james.name + ""s fastest times are: " + str(james.top3())) print(julie.name + ""s fastest times are: " + str(julie.top3())) print(mikey.name + ""s fastest times are: " + str(mikey.top3())) print(sarah.name + ""s fastest times are: " + str(sarah.top3()))
原文引用:http://www.godblessyuan.com/2015/05/03/head_first_python_chapter_6_lea...
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/37545.html
摘要:第六章抽象本章會(huì)介紹如何將語句組織成函數(shù)。關(guān)鍵字參數(shù)和默認(rèn)值目前為止,我們使用的參數(shù)都是位置參數(shù),因?yàn)樗鼈兊奈恢煤苤匾?,事?shí)上比它們的名字更重要。參數(shù)前的星號(hào)將所有值放置在同一個(gè)元祖中。函數(shù)內(nèi)的變量被稱為局部變量。 第六章:抽象 本章會(huì)介紹如何將語句組織成函數(shù)。還會(huì)詳細(xì)介紹參數(shù)(parameter)和作用域(scope)的概念,以及遞歸的概念及其在程序中的用途。 懶惰即美德 斐波那契數(shù)...
摘要:在復(fù)雜的情況下,需要具體策略維護(hù)內(nèi)部狀態(tài)時(shí),可能需要把策略和享元模式結(jié)合起來。函數(shù)比用戶定義的類的實(shí)例輕量,而且無需使用享元模式,因?yàn)楦鱾€(gè)策略函數(shù)在編譯模塊時(shí)只會(huì)創(chuàng)建一次。 一等函數(shù)實(shí)現(xiàn)設(shè)計(jì)模式 經(jīng)典的策略模式定義 定義一系列算法,把它們一一封裝起來,并且使它們可以相互替換。本模式使得算法可以獨(dú)立于使用它的客戶而變化。 案例 假如一個(gè)網(wǎng)店制定了下述折扣規(guī)則。 有 1000 或以上積分...
摘要:在指定位置刪除并返回這個(gè)數(shù)據(jù)項(xiàng),注意這里是有返回項(xiàng)的。移除某一個(gè)特定數(shù)據(jù)項(xiàng)。第二章發(fā)布并上傳代碼到在查閱大量資料發(fā)布和上傳還有很多附屬文件需要編寫和上傳以確保模塊能夠正常發(fā)布和更新。包含函數(shù)串鏈,特點(diǎn)是中包含函數(shù)。 寫在前面:吾嘗終日而思矣,不如須臾之所學(xué)也;吾嘗跂而望矣,不如登高之博見也。登高而招,臂非加長也,而見者遠(yuǎn);順風(fēng)而呼,聲非加疾也,而聞?wù)哒谩<佥涶R者,非利足也,而致千里;假...
摘要:弄了好久終于,踩了很多坑,感覺自己好菜,提供我的參考在外面設(shè)置,如,注意沒有引號(hào)和空格郵箱設(shè)置賬號(hào)獲取授權(quán)碼,在外部傳遞安全如,注意沒有引號(hào)和空格發(fā)送者郵箱接收者郵箱,,注意沒有引號(hào)參考的一個(gè)作者的文章插件系列,還有廖雪峰的教程 弄了好久終于OK,踩了很多坑,感覺自己好菜,提供我的參考 # -*- coding: utf-8 -*- import os from flask impor...
摘要:創(chuàng)建一個(gè)新對(duì)象將構(gòu)造函數(shù)的作用域賦給新對(duì)象因此就指向了這個(gè)新對(duì)象執(zhí)行構(gòu)造函數(shù)中的代碼為這個(gè)新對(duì)象添加屬性返回新對(duì)象。 本章內(nèi)容 理解對(duì)象屬性 理解并創(chuàng)建對(duì)象 理解繼承 ECMA-262把對(duì)象定義為:無序?qū)傩缘募希鋵傩钥梢园局?、?duì)象或者函數(shù) 理解對(duì)象 創(chuàng)建對(duì)象 創(chuàng)建自定義對(duì)象的最簡單方式就是創(chuàng)建一個(gè)Object的實(shí)例,再為它添加屬性和方法。 var person = new...
閱讀 2985·2023-04-26 02:04
閱讀 1293·2021-11-04 16:07
閱讀 3723·2021-09-22 15:09
閱讀 689·2019-08-30 15:54
閱讀 1912·2019-08-29 14:11
閱讀 2539·2019-08-26 12:19
閱讀 2265·2019-08-26 12:00
閱讀 771·2019-08-26 10:27