Head First Python 学习心得(1-6章)

写在前面:
“吾尝终日而思矣,不如须臾之所学也;吾尝跂而望矣,不如登高之博见也。登高而招,臂非加长也,而见者远;顺风而呼,声非加疾也,而闻者彰。假舆马者,非利足也,而致千里;假舟楫者,非能水也,而绝江河。君子生非异也,善假于物也。”
十几年的默默学习,而今希望更多是对自己知识的一个总结反思积累,能够探讨进步更是求之不得。虽然现在coding能力有限,但所幸站在巨人肩膀上,可总有一天,我也能成为巨人。
一篇简单python入门学习开始,作为自己千里之行第一步,sf.gg平台的第一次尝试。

第一章 对于列表的理解

python中的列表可以实现对各种数据的组织:
movies=['The Holy Grail','The life of brain','The meaning of life',2017,['dog','cat','duck']]
包括数字,字符串和列表,但数字和字符的组合只能包含在字符串之中。
列表中数据项的调用:
print(movies[1]) 显示”The life of brain”
下面列出一些关于list类列表的BIF:
len(movies)
输出列表中的数据项个数。
movies.append('')
在列表末尾添加单个数据项。
movies.extend(['',''])
在列表末尾增加一个数据项集合。
movies.pop(n)
在指定位置删除并返回这个数据项,注意这里是有返回项的。
movies.remove('')
移除某一个特定数据项。
insert('')
在特定位置增加一个数据项。
isinstance(name,list)
检查某个标识符(name)是否属于某种类型(例如list)。
list()
产生一个空列表的工厂函数。
range()
根据需要生成一个范围的数字,常用于循环次数
int()
将一个字符串或一个数字转换为整数

—-自己入门一定是从点到面的,因此这里并不是很全面的总结,希望以后更加完善。

关于python中的逻辑

迭代语句:

for each_file in movies:
    print(each_file)         

其中 each_file 是我们自己为列表中的数据项定义的名字。

count = 0
while count < len(movies):
    print(movies[1])
    count = count + 1

这里建议只要是能用for语句尽量用for语句。

判断语句:

if isinstance(each_item,list):
    print(each_item)
else:
   print('none')   

这里与c语言并无明显区别,多重判断加入elif。

创建自定义函数

def print_lol(the_list):
    xxxx
    xxxxx
    

自定义函数还有较多注意地方,在后续内容中有所提及。

第二章 发布并上传代码到pypi

在查阅大量资料发布和上传pypi还有很多附属文件需要编写和上传以确保模块能够正常发布和更新。这里只写了文中提到的能够保证发布和上传的最必要的几个步骤,未来可能会专门写一篇关于发布详细文章。

发布

1.为模块传建一个与模块文件(.py)相同名字的文件夹(例如:cat),并把文件放进去。
2.创建setup.py文件

from distutils.core import setup

setup(
    name = 'cat', 
    version = '1.0.0',  
    py_modules = ['cat'], 
    author = 'davystokess',  
    author_email = 'xxxxx', 
    url = 'http://www.xxxx.com', 
    description = 'A simple example'
      ) 

setup文件是为你的模块做出说明

3.发布 在此文件夹空白处 shift+右键 打开命令窗口输入:
《Head First Python 学习心得(1-6章)》
4.安装到本地文件:
《Head First Python 学习心得(1-6章)》
5.尝试导入并使用模块:

import cat

cat.print_lol(xxx)

其中cat.print_lol涉及命名空间,如果使用

from cat import print_lol
print_lol(xx)

则print_lol可以直接使用。

上传到pypi

书中的方法在我使用的3.6.2版本已经无法使用(仅限本人)。这里使用官方推荐方式:

py -m pip install twine   # 安装twine,必须有py -m 前缀否则无法使用,具体啥意思我也不知道(待改)

py -m twine upload dist/*  #利用twine上传

小体会:
(不保证完全正确)

  1. 上传的模块名字不能与已经上传的名字相同,否则会上传失败
  2. 上传本人无法建立有效的.pypirc文件 因此每次上传都需要输入账号密码(待学习)
  3. 再上传更新版本的时候需要模块重新发布。但需要删除dist文件夹的上一个版本的xxx.tar 文件否则会显示上传已经存在
  4. 注释有两种(1)是 # 注释一整行 (2)”’xxx”’注释一段
  5. 对于函数使用具有缺省值的参数例如 def print_lol(the_list,level=0)
  6. end=' '作为print函数参数可以关闭默认的自动换行
  7. 列表项目

第三章 文件与异常

文件

文件的打开:
data = open(sketch.text,'wb')
sketch.text是某一个文件,方式有’r”rb”w”wb”w+”a’分别代表读,二进制读,写二进制写,读和写,追加写入。注意data并不是一个列表,w会清空现有文件再写入,没有文件则会创建一个文件。

显示python当前工作文件夹,更改工作文件夹:

import os
os.getcwd()
os chdir(F:\code\python)

xxx.split(','n)
将xxx(一个数据项,或者一个列表等)中的数据依据’,’分为一个个数据项,n为分隔的个数,n=1则意味着在第一个,处将数据分为两半;不设置则有x个,分为x+1项的列表
xxx.readline()
读取xxx一个数据行(待改)
xxx.find('n')
寻找xxx数据中是否存在n 是返回参数:个数如10;否返回参数-1
xxx.seek()
用来是文件恢复到初始位置
not
将所得结果取反
xxx.close()
将文件关闭

处理异常

举例:

man=[]
other=[]
try:
    data=open('sketch.txt')
    for each_line in data:
        try:
            (role,line_spoken)=each_line.split(':',1)
            line_spoken= line_spoken.strip
            if role=='Man':
                man.append(line_spoken)
            elif role=='Other Man':
                other.append(line_spoken)
        except ValueError:
            pass
    data.close()
except IOError:
    print('The data file is missing!')
try:
    man_file=open('man_data.txt','w')
    other_file=open('other_data.txt','w')

    print(man,file=man_file)
    print(other,file=other_file)
except IOError as err:
    print('File error:'+str(err)) #通过这种方式可以将问题反馈给我们,用来分析错误类型
finally:
    man_file.close()
    other_file.close()    

try语句用来执行正常模块处理功能,except语句用来处理可能出现的错误:例如找不到指定文件或者数据类型不对等等;finally语句用来处理一定要执行语句。

第四章 将数据保存到文件

print('',file = file_name)
将数据写入文件

try:
    with open('man_data.txt','w') as man_file:   #注意形式
        print_lol(man,fh=man_file)
    with open('other_data.txt','w') as other_file:
        print_lol(other,fh=other_file) 
except IOError as err:
    print('File error:'+str(err))

使用with open() as xxx:语句可以妥善文件的开关

import pickle
try:
    with open('man_data.txt','wb') as man_file,open('other_data.txt','wb') as other_file:
    #注意创建储存的文件是xxxx.pickle或xxx.txt格式都可以
        pickle.dump(man,man_file)
        pickle.dump(other,other_file)
except IOError as err:
    print('file error:'+str(err))
except pickle.PickleError as perr:
    print('Pickleing error:'+ste(perr))

new_man=[]


with open('man_data.txt','rb') as man_file:
    new_man=pickle.load(man_file)
print_lol(new_man)

呵呵 使用pickle.dump(数据,文件名)可以将数据压缩保存;使用pickle.load(数据名)可以将数据提取出来。注意写,读打开方式是wb和rb 。

第五章 处理数据

def get_coach_data(filename):
    with open(filename) as f:
        data=f.readline()
        return(data.strip().split(','))  
#方法串链 从左往右读 特点以点为分隔,()中无包含关系

对于第五章的数据(只有计时数据)进行处理 打开-读取(变为列表但只有一项?)-去空格-以’,’为分隔变为多个数据项的列表返回。

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)

自定义sanitize函数用于将数据中的’-”:’都变为’.’。

print(sorted(set([sanitize(t) for t in james]))[0:3])
包含函数串链,特点是()中包含函数。一种写代码的方式:列表推导 自行体会。但其中的set()函数是将数据(无论是导入的还是列表数据)转换为一个集合,这样就可以去除数据中的重复项。

第六章 打包代码和数据

当数据发生改变(增加或者减少类型)时,使用 字典 使用字典会非常方便:

def get_coach_data(filename):
    with open(filename) as f:
        data=f.readline().strip().split(',')
        data1={}
        data1['name']=data.pop(0)
        data1['DOB'] =data.pop(0)
        data1['Times']=str(sorted(set([sanitize(t) for t in data]))[0:3])
    return(data1)
sarah = get_coach_data('sarah2.txt')
print(sarah['name']+"'s fastest time are:"+sarah['Times'])
# 对字典的调用例如sarah['name'],方式简单实用。

这里面get_coach_data()函数创建并处理数据追中返回一个字典,对字典的调用。

但将数据与代码打包在一起是更好的,函数与数据关联才有意义,因此引入类的使用:

class Athlete:
    def __init__(self,a_name,a_dob=None,a_times= [ ]): 
    #  __init__这里一定要注意 两个短横线 
        self.name =a_name
        self.dob = a_dob
        self.times=a_times
    def top3(self):
        return(sorted(set([sanitize(t) for t in self.times]))[0:3])
    def add_time(self,time_value):
        self.times.append(time_value)
    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)
#此处是重点  注意观察一定制类的不同
class Athletelist(list):
# 注意()中的是你将派生的类的类型
    def __init__(self,a_name,a_dob=None,a_times= []):
        list.__init__([])
        self.name =a_name
        self.dob = a_dob
        self.extend(a_times)
    def top3(self):
        return(sorted(set([sanitize(t) for t in self]))[0:3])

        
def get_coach_data(filename):
    with open(filename) as f:
        data = f.readline().strip().split(',')
    return(Athletelist(data.pop(0),data.pop(0),data))
    #注意观察类的调用方式
        
sarah = get_coach_data('sarah2.txt')
print(sarah.name+"'s fastest time are:"+str(sarah.top3()))

vera= Athletelist('vera vi')
vera.extend(['1.31','1-21','2:22'])

print(vera.top3())

这里涉及了子类的创建方法,不仅包含编写的功能,还包含list本身的功能。

小结:
小小入门。

    原文作者:临冬城的雪囧
    原文地址: https://segmentfault.com/a/1190000010982095
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞