设为首页 收藏本站
查看: 592|回复: 0

[经验分享] Python 字典的使用

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-7-27 08:39:22 | 显示全部楼层 |阅读模式
字典:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#可以用大括号创建字典,也可以用工厂函数创建;
cleese={}
palin=dict()

#给字典加入一些数据
cleese['Name'] = 'John Cleese'
cleese['Occupations'] = ['actor','comedian','writer',]

#查看里面有哪些数据项
In [9]: cleese
Out[9]: {'Name': 'John Cleese', 'Occupations': ['actor', 'comedian', 'writer']}

palin = {'Name':'Michael Palin','Occupations':['comedian','actor','writer','tv']}

In [11]: palin
Out[11]: {'Name': 'Michael Palin', 'Occupations': ['comedian', 'actor', 'writer', 'tv']}

#可以通过键来调用对应的数据
In [13]: palin['Name']
Out[13]: 'Michael Palin'

#如果字典中一个键对应着多个数据项,也可以使用类似列表的记号访问。
In [15]: palin['Occupations'][-1]
Out[15]: 'tv'

In [16]: palin['Occupations'][1]
Out[16]: 'actor'

In [17]: palin['Occupations'][0]
Out[17]: 'comedian'



一、对以下数据做处理,输出保留人名和比赛数据排序后的前三项。
Sarah Sweeney,2002-6-17,2:58,2.58,2:39,2-25,2-25,2:54,2.18,2:55,2:55
第一版代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/local/python3/bin/python3
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_file_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)

sarah1 = get_file_data('sarah2')
#这里是将列表中前两项数据,人名和生日使用pop弹出到sarah_name,sarah_dob两个变量中。
(sarah_name,sarah_dob) = sarah1.pop(0),sarah1.pop(0)
#这里要做字符串拼接,所以后面的序列处理完之后,需要使用str()转换成字符串。
print(sarah_name + "'s fastest times are:" + str(sorted(set([ sanitize(i) for i in sarah1 ]))[0:3]))



输出结果:
Sarah Sweeney's fastest times are:['2.18', '2.25', '2.39']

二、上面定义的函数不变,我们使用字典的方式来完成
第二版代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/local/python3/bin/python3
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_file_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)

sarah1 = get_file_data('sarah2')
#定义字典
sarah_dic=dict()
#将列表中前两个数据项,弹出保存到字典对应的键上。
sarah_dic['name'] = sarah1.pop(0)
sarah_dic['dob'] = sarah1.pop(0)
#姓名和日期都弹出了,sarah1里面剩下的就是时间数据了,保存在sarah_dic字典中,键为time;
sarah_dic['time'] = sarah1
print(sarah_dic['name'] + "'s fastest time are: " + str(sorted(set([sanitize(i) for i in sarah1]))[0:3]))



输出结果与上面相同



三、把字典的创建移到get_file_data() 函数中,返回一个字典而不是列表。 并且把数据切片,去重复项,排序也移到get_file_data函数中,调用函数完成4个选手的成绩输出。
第三版代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/local/python3/bin/python3
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_file_data(filename):
    try:
        with open(filename) as f:
            data = f.readline()
        templ = data.strip().split(',')
        return({'name':templ.pop(0),
                'dob':templ.pop(0),
                'time':str(sorted(set([sanitize(i) for i in templ]))[0:3])})
    except IOError as ioerr:
        print('File error' + str(ioerr))
        return(None)


james1 = get_file_data('james2')
julie1 = get_file_data('julie2')
mikey1 = get_file_data('mikey2')
sarah1 = get_file_data('sarah2')

print(james1['name'] + "'s fastest time are: " + james1['time'])
print(julie1['name'] + "'s fastest time are: " + julie1['time'])
print(mikey1['name'] + "'s fastest time are: " + mikey1['time'])
print(sarah1['name'] + "'s fastest time are: " + sarah1['time'])



输出结果:
wKiom1W07--wD7nnAADf4Gtbl_Y958.jpg


难点:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def get_file_data(filename):
    try:
        with open(filename) as f:
            data = f.readline()
        templ = data.strip().split(',')
#可以看到这里是返回字典了,发现连字典名都没有,直接返回的是键和对应的数据。        
        return({'name':templ.pop(0),
                'dob':templ.pop(0),
                'time':str(sorted(set([sanitize(i) for i in templ]))[0:3])})
    except IOError as ioerr:
        print('File error' + str(ioerr))
        return(None)
         
#由于返回过来的直接是字典数据,这里用任何的变量调函数,都会变成字典,而函数返回键值对应的数据就保存在该字典中。
james1 = get_file_data('james2')   

#这里就可以使用字典和键"james1['name']"来输出数据了。
print(james1['name'] + "'s fastest time are: " + james1['time'])



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-90955-1-1.html 上篇帖子: Python学习之List 下篇帖子: Python学习日志之Python数据结构初识
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表