Python3.6全栈开发实例[024]

24.文件a1.txt内容(注意每行中的空格是不一样的,需要对空格进行处理)
序号 部门   人数   平均年龄           备注
1 python   30   26   单身狗
2 Linux      26    30 没对象
3 运营部   20    24              女生多
通过代码,将其构建成这种数据类型:

li = []
import re
with open('t4','r',encoding='utf-8') as f:
    first = re.sub(r"\s{2,}", " ", f.readline().strip())
    first = first.split(' ')
    # print(first)
    for i in f.readlines():
        dic = {}
        i = re.sub(r"\s{2,}", " ", i.strip())
        l1 = i.split(' ')
        # print(l1)
        for i in range(len(first)):
            dic[first[i]] = l1[i]
        li.append(dic)
print(li)

猜你喜欢

转载自www.cnblogs.com/apollo1616/p/9462832.html