亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

head first python(第六章)–學(xué)習(xí)筆記

piapia / 1956人閱讀

摘要:代碼改為根據(jù)數(shù)據(jù)結(jié)構(gòu),第一個數(shù)據(jù)是名字,第二個是生日,第二個之后是成績,所以分別將相關(guān)數(shù)據(jù)賦值到字典里面。是否知道何時使用列表而何時使用字典,這正式從好的程序員中區(qū)分出優(yōu)秀程序員的一個標準。特定函數(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ù)整理,實現(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 = {} #大括號??!

也可以是

palin = dict()

關(guān)聯(lián)key和value的話是

cleese["Name"] = "John Cleese"  # 一個key 對應(yīng)一個字符串

或者

cleese["Name"] = ["John Cleese","John Cleese1","John Cleese2","John Cleese3","John Cleese4"] #一個key對應(yīng)一個list

或者

cleese = {"Name":"abc","Address":"asdasdasda"}  #注意是用冒號

另外數(shù)據(jù)值與key關(guān)聯(lián)后,需要訪問數(shù)據(jù)值里面的某個數(shù)據(jù)項的話,可以是

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),第一個數(shù)據(jù)是名字,第二個是生日,第二個之后是成績,所以分別將相關(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]))
  

字典的方法優(yōu)勢在于合理使用數(shù)據(jù)結(jié)構(gòu)。是否知道何時使用列表而何時使用字典,這正式從好的程序員中區(qū)分出優(yōu)秀程序員的一個標準。
字典其實也叫“映射”,“散列”,“關(guān)聯(lián)數(shù)組”

為了更加方便的處理多個人的成績的數(shù)據(jù),所以將字典數(shù)據(jù)轉(zhuǎn)移到函數(shù)里面去,直接通過函數(shù)生成出字典,并返回需要的數(shù)據(jù)
#!/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編程模型的東西,類的概念在這里不詳細描述。

類可以

1.降低復(fù)雜性
2.方便維護和擴展

python的類需要有一個self參數(shù),這個參數(shù)是用來標識是屬于哪個對象實例的

例如:

class Athlete:
    def __init__(self,value=0):
        self.thing = value      #定義這個類的屬性thing
    def how_big(self)           #定義一個方法how_big
        return(len(self.thing))

btw:init 是類的python固定實現(xiàn)方法,所以是必須的。

你寫的代碼                   -->     python執(zhí)行的代碼
d = Athlete("Holy Grail")           Athlete.__init__(d,"Holy Grail")
                                    |         |      |  
                                    類       方法    目標標識符 
                                    |         |     |
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()))
  

科普:

1.通過在各個對象的屬性中保留原始數(shù)據(jù),可以支持類擴展來滿足將來的其他需求。如果處理數(shù)據(jù)并作為對象初始化代碼的一部分,說明你已對程序員將如何使用這個類做出了假設(shè),而日后這些假設(shè)肯定會對你造成障礙。

在類里面增加一個靈活的增加成績數(shù)據(jù)的函數(shù)

可以是增加單個成績,或是增加多個成績
單個成績用add_time,傳入的是字符串
多個成績是add_times,傳入的是list

以下是單個成績的樣例:

#!/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é)果會改變
觀察到這個類有點像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)    #因為集成list類了,所以這里可以直接使用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)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/37545.html

相關(guān)文章

  • Python基礎(chǔ)教程》六章--讀書筆記

    摘要:第六章抽象本章會介紹如何將語句組織成函數(shù)。關(guān)鍵字參數(shù)和默認值目前為止,我們使用的參數(shù)都是位置參數(shù),因為它們的位置很重要,事實上比它們的名字更重要。參數(shù)前的星號將所有值放置在同一個元祖中。函數(shù)內(nèi)的變量被稱為局部變量。 第六章:抽象 本章會介紹如何將語句組織成函數(shù)。還會詳細介紹參數(shù)(parameter)和作用域(scope)的概念,以及遞歸的概念及其在程序中的用途。 懶惰即美德 斐波那契數(shù)...

    AnthonyHan 評論0 收藏0
  • 流暢的python讀書筆記-六章-使用一等函數(shù)實現(xiàn)設(shè)計模式

    摘要:在復(fù)雜的情況下,需要具體策略維護內(nèi)部狀態(tài)時,可能需要把策略和享元模式結(jié)合起來。函數(shù)比用戶定義的類的實例輕量,而且無需使用享元模式,因為各個策略函數(shù)在編譯模塊時只會創(chuàng)建一次。 一等函數(shù)實現(xiàn)設(shè)計模式 經(jīng)典的策略模式定義 定義一系列算法,把它們一一封裝起來,并且使它們可以相互替換。本模式使得算法可以獨立于使用它的客戶而變化。 案例 假如一個網(wǎng)店制定了下述折扣規(guī)則。 有 1000 或以上積分...

    cnsworder 評論0 收藏0
  • Head First Python 學(xué)習(xí)心得(1-6章)

    摘要:在指定位置刪除并返回這個數(shù)據(jù)項,注意這里是有返回項的。移除某一個特定數(shù)據(jù)項。第二章發(fā)布并上傳代碼到在查閱大量資料發(fā)布和上傳還有很多附屬文件需要編寫和上傳以確保模塊能夠正常發(fā)布和更新。包含函數(shù)串鏈,特點是中包含函數(shù)。 寫在前面:吾嘗終日而思矣,不如須臾之所學(xué)也;吾嘗跂而望矣,不如登高之博見也。登高而招,臂非加長也,而見者遠;順風(fēng)而呼,聲非加疾也,而聞?wù)哒谩<佥涶R者,非利足也,而致千里;假...

    pumpkin9 評論0 收藏0
  • Flask Web開發(fā):六章的電子郵件配置

    摘要:弄了好久終于,踩了很多坑,感覺自己好菜,提供我的參考在外面設(shè)置,如,注意沒有引號和空格郵箱設(shè)置賬號獲取授權(quán)碼,在外部傳遞安全如,注意沒有引號和空格發(fā)送者郵箱接收者郵箱,,注意沒有引號參考的一個作者的文章插件系列,還有廖雪峰的教程 弄了好久終于OK,踩了很多坑,感覺自己好菜,提供我的參考 # -*- coding: utf-8 -*- import os from flask impor...

    airborne007 評論0 收藏0
  • 高程讀書筆記 六章 面向?qū)ο蟪绦蛟O(shè)計

    摘要:創(chuàng)建一個新對象將構(gòu)造函數(shù)的作用域賦給新對象因此就指向了這個新對象執(zhí)行構(gòu)造函數(shù)中的代碼為這個新對象添加屬性返回新對象。 本章內(nèi)容 理解對象屬性 理解并創(chuàng)建對象 理解繼承 ECMA-262把對象定義為:無序?qū)傩缘募希鋵傩钥梢园局?、對象或者函?shù) 理解對象 創(chuàng)建對象 創(chuàng)建自定義對象的最簡單方式就是創(chuàng)建一個Object的實例,再為它添加屬性和方法。 var person = new...

    468122151 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<