本文来源《Head Firest Python》书籍
字典 这是一个内置的数据结构,允许将数据与键而不是数字关联。这样可以使内存中的数据与实际数据的结构保持一致。
python 字典在其他编程语言中还有不同的名字,如“映射”,“散列”,“关联数组”
定义字典
方法 1 cleese={}
方法2 cleese=dict()
例子,仍旧使用上篇列表推导中的例子,只是将文件内容做如下修改增加了名字跟出生日期,找出两个文件中最快的3个时间
例子,现在有两个文件 james.txt ,julie.txt ,这两个文件
james.txt 内容 james,1990-6-3,2.01,2-22,2.34,2:38,3.01,3-10,3:20
julie.txt 内容 julie,1991-1-3,2.22,2:11,2.23,2.59,3-21,3:22,2-13
###定义函数sanitize,用来转换数据中的-与:
def sanitize(time_string):
if '_' in time_string:
splitter='_'
elif ':' in time_string:
splitter=':'
(mines,secs)=time_string.split(splitter)
return(mins + '.' + secs)
###定义函数,get_coach_data读取文件
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)))
print(None)
james=get_coach_data('james.txt')
###创建字典
james_data={}
james_data['Name']=james.pop(0)
james_data['birthday']=james.pop(0)
james_data['Times']=james
print(james_data['Name'] + "'s fastest times are: " +
str(sorted(set ( [sanitize(t) for t in james_data['Times'] ] )) [0:3]))
代码调整优化:
###调整get_coach_data 函数,将创建字典的代码,以及最后排序打印的代码都放入其中
def get_coach_data(filename):
try:
with open(filename) as f:
data=f.readline()
templ=data.strip().split(',')
return( {'Name':templ.pop(0),
'birtyday':templ.pop(0),
'times': str(sorted(set ( [sanitize(t) for t in templ ] )) [0:3]) } )
except IOError as ioerr:
print('File error:'+str(ioerr)))
print(None)
james=get_coach_data('james.txt')