首页 > 其他 > 详细

文件操作

时间:2021-04-11 22:03:29      阅读:27      评论:0      收藏:0      [点我收藏+]

1、车牌区域划分, 现给出以下车牌. 根据车牌的信息, 分析出各省的车牌持有量.
结果: {‘山东‘: 2, ‘北京‘: 1, ‘黑龙江‘: 2, ‘上海‘: 1}
cars = [鲁A32444, 鲁B12333, 京B8989M, 黑C49678, 黑C46555, 沪B25041]
local_s = {: 上海, : 黑龙江, : 山东, : 湖北, : 湖南, : 北京}


area = [] con = {} for a in cars: area.append(a[0]) for i in area: add = local_s.get(i) con.setdefault(add, area.count(i)) print(con)
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,‘year‘:2012},

? {‘name‘:‘tesla‘,‘price‘:1000000,‘amount‘:1}......]

? 并计算出总价钱。
content_list = []
_list = []
with open(a1.txt, encoding=utf=8, mode=r) as f1:
    for row in f1:
        list_row = row.split()
        _list.append(list_row)
    for row1 in _list:
        content_dict = {}
        for row2 in row1:
            content = row2.split(:)
            if content[1].isdigit(): content[1] = int(content[1])
            content_dict[content[0]] = content[1]
        content_list.append(content_dict)
print(content_list)
price = 0
for i in range(len(content_list)):
    price += content_list[i].get(price)
print(price)
4、文件a1.txt内容

------

序号 部门 人数 平均年龄 备注

1 python 30 26 单身狗

2 Linux 26 30 没对象

3 运营部 20 24 女生多

.......

------

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

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

......]
list_new = []
with open(a2.txt, encoding=utf=8, mode=r) as f2:
    row_1_list = f2.readline().split()
    for i in range(3):
        lis1 = f2.readline().strip().split()
        dict_new = {}
        for n in range(len(lis1)):
            dict_new[row_1_list[n]] = lis1[n]
        list_new.append(dict_new)
print(list_new)

 

文件操作

原文:https://www.cnblogs.com/XiaoYang-sir/p/14644577.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!