先来看新需求:
现在把数据改成了这样
James Lee,2002-3-14,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22,2-01,2.01,2:16
Julie Jones,2002-8-17,2.59,2.11,2:11,2:23,3-10,2-23,3:10,3.21,3-21,3.01,3.02,2:59
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
Mikey McManus,2002-2-24,2:22,3.01,3:01,3.02,3:02,3.02,3:22,2.49,2:38,2:40,2.22,2-31
思路就是用pop方法去掉前两个数据。
#coding=utf-8
list1 = ['Google', 'Runoob', 'Taobao']
list_pop=list1.pop(1)
print "删除的项为 :", list_pop
print "列表现在为 : ", list1
删除的项为 : Runoob
列表现在为 : ['Google', 'Taobao']
那么只要改一点就行了。
def getFast(fileName):
arr = []
try:
with open(fileName) as data:
line = data.readline()
scores = line.split(',')
name=scores.pop(0)
birth=scores.pop(0)
print(scores)
# scores=scores[3:len(scores)-1)]
arr = [sanitize(score) for score in scores]
_arr = set(arr)
return sorted(_arr)[0:3]
except IOError as err:
print('file error.'+str(err))
def sanitize(score):
splitter = '.'
if '-' in score:
splitter = '-'
if ':' in score:
splitter = ':'
elif '.' in splitter:
return score
(mins, sec) = score.split(splitter)
return mins+'.'+sec
print(getFast('sarah.txt'))
当你谈起映射/散列等名词是,你讨论的是 字典
和对象类似,字典也是键值对.字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
键一般是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
一个简单的字典实例:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
也可如此创建字典:
dict1 = { 'abc': 456 }dict2 = { 'abc': 123, 98.6: 37 }
把相应的键放入熟悉的方括弧,如下实例:
>>>dict = {'a': 1, 'b': 2, 'b': '3'}
>>> dict['b']
'3'
>>> dict
{'a': 1, 'b': '3'}
以上实例输出结果:
dict['Name']: Zara
dict['Age']: 7
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8 # 更新
dict['School'] = "RUNOOB" # 添加
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
以上实例输出结果:
dict['Age']: 8
dict['School']: RUNOOB
能删单一的元素也能清空字典,清空只需一项操作。
显示删除一个字典用del命令,如下实例:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # 删除键是'Name'的条目
dict.clear() # 清空词典所有条目
del dict # 删除词典
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
但这会引发一个异常,因为用del后字典不再存在:
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age']
TypeError: 'type' object is unsubscriptable
注:del()方法后面也会讨论。
def getFast(fileName):
arr = []
try:
with open(fileName) as data:
line = data.readline()
scores = line.split(',')
table={
'name': scores.pop(0),
'birth': scores.pop(0),
}
arr = [sanitize(score) for score in scores]
_arr = set(arr)
table['scores'] = sorted(_arr)[0:3]
return table
except IOError as err:
print('file error.'+str(err))
def sanitize(score):
splitter = '.'
if '-' in score:
splitter = '-'
if ':' in score:
splitter = ':'
elif '.' in splitter:
return score
(mins, sec) = score.split(splitter)
return mins+'.'+sec
print(getFast('sarah.txt'))
计划通。
python中面向对象的类,有类似this的self。用class语法创建,但没有new关键字
class Athlete:
def __init__(self,a_name,a_birth=None,a_scores=[]):
self.name=a_name
self.birth=a_birth
self.scores=a_birth
a = Athlete('Sarah Sweeney', '2002-6-17', ['2.18', '2.21', '2.22'])
__init__
方法是第一个参数必然是 self
。
好了,现在要给Athlete多加一个top3方法。
class Athlete:
def __init__(self,a_name,a_birth=None,a_scores=[]):
self.name=a_name
self.birth=a_birth
self.scores=a_scores
def top3(self):
return sorted(set([sanitize(score) for score in self.scores]))[0:3]
def getFast(fileName):
try:
with open(fileName) as data:
line = data.readline()
scores = line.split(',')
return Athlete(scores.pop(0), scores.pop(0), scores)
except IOError as err:
print('file error.'+str(err))
def sanitize(score):
splitter = '.'
if '-' in score:
splitter = '-'
if ':' in score:
splitter = ':'
elif '.' in splitter:
return score
(mins, sec) = score.split(splitter)
return mins+'.'+sec
print(getFast('sarah.txt').name)
加两个方法:
class Athlete:
def __init__(self, a_name, a_birth=None, a_scores=[], a_add_time=None, a_add_times=[]):
self.name=a_name
self.birth=a_birth
self.scores=a_scores
self.addtime=a_add_time
self.addtimes=a_add_times
def top3(self):
return sorted(set([sanitize(score) for score in self.scores]))[0:3]
def add_time(self):
self.scores.append(self.addtime)
return self.scores
def add_times(self):
self.scores.extend(self.addtimes)
return self.scores
好像挺不错。
遗憾的是:这个类可以死了。
因为类可以从列表中继承一大堆方法。
class AthleteList(list):#提供一个类名
def __init__(self, a_name, a_birth=None, a_scores=[]):
# 初始化派生的类
list.__init__(list([]))
self.name = a_name
self.birth = a_birth
self.scores = a_scores
b=AthleteList('dangjingtao')
b.append('love'),
b.extend([1,2,3])
print(b)
# ['love', 1, 2, 3]
可以这么理解为:dangjingtao这个类就是一个列表,但是还额外包含了3个给定的属性。
好了,那么重写这个开始的这个类吧。
class AthleteList(list):#提供一个类名
def __init__(self, a_name, a_birth=None, a_scores=[]):
# 初始化派生的类
list.__init__(list([]))
self.name = a_name
self.birth = a_birth
self.extend(a_scores)
def top3(self):
return sorted(set([sanitize(score) for score in self]))[0:3]
好了,前六章就此结束。入门基本结束了。