文件操作-作业

作业1,文件a.txt内容:每一行内容分别为商品名字,价格,个数

apple 10 3

tesla 100000 1

mac 3000 2

lenovo 30000 3

chicken 10 3

通过代码,将其构建成这种数据类型:

[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并计算出总价钱。

'''
实现方法:
循环句柄,控制循环次数,对item进行切割,形成列表,
在进行for循环添加字典
'''
with open('a.txt', 'r', encoding='utf-8') as f:
    li = []
    for item in f:  # item = apple 10 3
        dic = {'name': None, 'price': None, 'amount': None}
        lst = item.split()  # lst = ['apple', '10', '3']
        dic['name'] = lst[0]
        dic['price'] = lst[1]
        dic['amount'] = lst[2]
        li.append(dic)
    print(li)

作业2,文件a1.txt内容:

name:apple price:10 amount:3 year:2012
name:tesla price:100000 amount:1 year:2013

......

通过代码,将其构建成这种数据类型:

[{'name': 'apple', 'price': '10', 'amount': '3'}, {'name': 'tesla', 'price': '100000', 'amount': '1'}]

with open('e.txt', 'r', encoding='utf-8') as f:
    lst = []
    sum = 0
    for item in f:
        dic = {}
        lst1 = item.split(' ')  # ['name:apple', 'price:10', 'amount:3', 'year:2012\n']
        for el in lst1:  # item = 'name:apple'
            lst2 = el.split(':')  # lst2 = [name, apple]
            if lst2[0] == 'year':
                continue
            dic[lst2[0]] = lst2[1].strip()
        lst.append(dic)
        sum += int(dic['price'])*int(dic['amount'])
    print(lst)
    print(sum)

作业3,文件a.1txt内容形式:

序号     部门      人数      平均年龄      备注
1       python    30         26         单身狗
2       Linux     26         30         没对象
3       运营部     20         24         女生多

通过代码,将其构建成这种数据类型:

[{'序号':'1','部门':Python,'人数':30,'平均年龄':26,'备注':'单身狗'},
......]

with open('d.txt', 'r', encoding='utf-8') as f:
    lst = f.readlines()
    lst1 = []  # 最后打印的列表
    new = []  # key的列表
    for item in lst[0].split():  # 将第一行的名称添加到new列表里面,之后for循环new列表元素组成字典的key
        if item != ' ':
            new.append(item)
    # print(new)  # ['序号', '部门', '人数', '平均年龄', '备注']
    # print(lst[1:])
    index = 0   # 实现列表长度的循环
    for item in lst[1:]:
        # n = []
        dic = {}  # 循环定义字典,添加到列表中
        for el in item.split(' '):  # el = ['1', ...]
            if el != '':  # n = ['1', 'python', '30', '26', '单身狗\n']
                # n.append(el)
                dic[new[index]] = el.strip()  # 匹配索引位置以键值对的形式添加到列表中
                index += 1
                if index == len(new):
                    index = 0
        lst1.append(dic)
    print(lst1)

猜你喜欢

转载自www.cnblogs.com/chenrun/p/9157278.html