head first python chap 5 学习笔记

一、python的两种排序方法

data=[6,5,4,3,2,1]
data.sort()"""one method"""
print(data)
data2=sorted(data)""" another method"""
print(data2)

 

二、处理数据格式并对数据进行排序(page 151)

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(min+'.'+secs)

三、

james = []  // create new, initially empty lists.

四、几个数据处理的例子(倍数,函数操作等等)

import sanitize
mins=[1,2,3]
secs=[m*60 for m in mins]
print(secs)
meters=[1,10,3]
feet=[m*3.281 for m in meters]

print(feet)
lower=["I","don't","like","spam"]
upper=[s.upper() for s in lower]
upper
dirty=['2-22','2:22','2.22']
clean=[sanitize.sanitize(t) for t in dirty]// 其中sanitize为一个py文件,调用文件中的名为sanitize的函数。
clean
clean=[float(s) for s in clean]
clean=[float(sanitize.sanitize(t)) for t in['2-22','3:33','4.44']]
clean

五、

james[0:3]   左闭右开

六、 remove duplicates from list

方法一:

iterate to remove duplicates(该方法有点笨,需要重复进行很多次)

james=sorted([sanitize(t) for t in james])
julie=sorted([sanitize(t) for t in julie])
mikey=sorted([sanitize(t) for t in mikey])
sarah=sorted([sanitize(t) for t in sarah])
unique_james=[]
for each_t in james:
    if each_t not in unique_james:
        unique_james.append(each_t)
print(unique_james[0:3])
unique_julie=[]
for each_j in julie:
    if each_j not in unique_julie:
        unique_julie.append(each_j)
print(unique_julie[0:3])
unique_mikey=[]
for each_j in mikey:
    if each_j not in unique_mikey:
        unique_mikey.append(each_j)
print(unique_julie[0:3])
unique_julie=[]
for each_j in sarah:
    if each_j not in unique_sarah:
        unique_sarah.append(each_j)
print(unique_julie[0:3])

有没有更快更简单的方法?
方法二:

用set()

set([sanitize(t) for t in james])

七、page 170左右的代码

from sanitize import *
distances=set()
distances={10.6,11,8,10.6,"two",7}
print(distances)
def gcd(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)
james=gcd("F:\\james.txt")
james=[sanitize(t) for t in james]
distances=set(james)
print(distances)

"""with open("F:\\james.txt") as james:
    james=james.readline()
    james=james.strip().split(',')"""

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值