head first python(第六章)–学习笔记

样例数据

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

需要将数据整理,实现人名+出生日期+成绩的输出

以往的做法是:

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]))

这次加入了字典的做法

字典将数据值与键关联:

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]"

创建字典的方式可以是

cleese = {} #大括号!!

也可以是

palin = dict()

关联key和value的话是

cleese['Name'] = 'John Cleese'  # 一个key 对应一个字符串

或者

cleese['Name'] = ['John Cleese','John Cleese1','John Cleese2','John Cleese3','John Cleese4'] #一个key对应一个list

或者

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

另外数据值与key关联后,需要访问数据值里面的某个数据项的话,可以是

cleese['Name'][-1] 

类似多维数组使用。

代码改为

#!/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)   #根据数据结构,第一个数据是名字,第二个是生日,第二个之后是成绩,所以分别将相关数据赋值到字典里面。
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]))

字典的方法优势在于合理使用数据结构。是否知道何时使用列表而何时使用字典,这正式从好的程序员中区分出优秀程序员的一个标准。
字典其实也叫“映射”,“散列”,“关联数组”

为了更加方便的处理多个人的成绩的数据,所以将字典数据转移到函数里面去,直接通过函数生成出字典,并返回需要的数据

#!/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'])

这就是将代码和数据打包在一起。特定函数应用特定数据。

更加正规的做法是建立类。

类是面向对象oop编程模型的东西,类的概念在这里不详细描述。

类可以

1.降低复杂性
2.方便维护和扩展

python的类需要有一个self参数,这个参数是用来标识是属于哪个对象实例的

例如:

class Athlete:
    def __init__(self,value=0):
        self.thing = value      #定义这个类的属性thing
    def how_big(self)           #定义一个方法how_big
        return(len(self.thing))

btw:init 是类的python固定实现方法,所以是必须的。

你写的代码                   -->     python执行的代码
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.通过在各个对象的属性中保留原始数据,可以支持类扩展来满足将来的其他需求。如果处理数据并作为对象初始化代码的一部分,说明你已对程序员将如何使用这个类做出了假设,而日后这些假设肯定会对你造成障碍。

在类里面增加一个灵活的增加成绩数据的函数

可以是增加单个成绩,或是增加多个成绩
单个成绩用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')      #这里调用
print(sarah.name + "'s fastest times are: " + str(sarah.top3()))    #输出结果会改变

观察到这个类有点像list,所以有重复制造车轮的嫌疑,并且功能单一,所以决定集成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):    #继续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_learning/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • 〇、前言 本文共108张图,流量党请慎重! 历时1个半月,我把自己学习Python基础知识的框架详细梳理了一遍。 ...
    Raxxie阅读 18,784评论 17 410
  • 人生苦短我用 Python 注:最后附电子书地址 一、Pythonic Thinking 第1条: 确认自己所用的...
    molscar阅读 1,952评论 0 3
  • 2016年5月24日 星期三 大雨 今天,我们满怀着希望来到学校,因为我们把足球比赛踢到了决赛。我们的三班比二...
    仔哥阅读 218评论 0 0
  • 一、觉察 亲爱的自己:你好,你知道吗?现在你正处于心情愉悦中,早上送完孩子和老婆一起去湿地公园里挖野菜。 二、...
    孙兰昌阅读 190评论 0 0
  • 相遇是一种缘分更是一场修行。 在艳阳吝啬,阴雨霏霏的今秋,注定又有一场与新生修...
    繁华过往阅读 540评论 0 2