【Python实战12】使用字典关联数据

这篇博客探讨了如何在Python中使用字典来关联和处理数据。通过示例展示了两种创建字典的方法,包括使用大括号直接创建和使用字典工厂方法。
摘要由CSDN通过智能技术生成

现在我的手里有了新的一组数据,数据内容如下:

james.txt:

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.txt:
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
mikey.txt:
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
sarah.txt:
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
我们可以看到数据格式为姓名,出生年月和一系列的时间列表,现在希望的是打印每个文件中的人的姓名、出生年月和最快的三个时间。现在我们先编写一段简单的代码来实现这个功能,代码如下:
"""转换时间格式"""
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_coach_data(filename):
    try:
        with open(filename) as file:
            data = file.readline()
        return(data.strip().split(','))
    except IOError as error:
        print('File Error:'+str(error))
        return(None)

"""读取sarah.txt的内容"""
sarah = get_coach_data('sarah.txt')

"取出姓名和生日"
(sarah_name,sarah_birthday) = sarah.pop(0),sarah.pop(0)

"""打印姓名、生日和最快的三个时间"""
print(sarah_name+"的生日是:"+sarah_birthday+
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值