文件修改,map函数的一些练习
1.写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作
# 输入文件名,被修改的内容,修改成的内容
def update_file(file_name, updated, updating):
import os
if not os.path.exists(file_name):
print('输入的文件不存在!')
exit()
new_file = file_name + '_bak'
change_num = 0
with open(file_name, 'r', encoding='utf-8') as f:
with open(new_file, 'w', encoding='utf-8') as f_new:
for line in f:
if updated in line:
new_line = line.replace(updated, updating)
change_num += 1
else:
new_line = line
f_new.write(new_line)
os.replace(new_file, file_name) # 覆盖原来的文件
return '修改了%s处' % change_num
print(update_file('update.txt', 'M', 'm'))
2.用map来处理字符串列表,把列表中所有人都变成sb,比方alex_sb
l_name = ['alex', 'eric', 'penny'] res = map(lambda x: x + '_sb', l_name) print(list(res))
3.用filter函数处理数字列表,将列表中所有的偶数筛选出来
num = [1, 3, 5, 6, 7, 8] res = filter(lambda x: x % 2 == 0, num) print(list(res))
4.如下,每个小字典的name对应股票名字,shares对应多少股,price对应股票的价格
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
计算购买每支股票的总价
用filter过滤出,单价大于100的股票有哪些
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
for item in portfolio:
item['total_price'] = item['price'] * item['shares']
print(portfolio)
print(list(filter(lambda x: x['price'] > 100, portfolio)))
序列化,反序列化
pickle的方式:
import pickle info = {'name': 'alex', 'age': '22'} with open('test.test', 'wb') as f: f.write(pickle.dumps(info)) # 序列化 # pickle.dump(info, f) # 跟上一句完全一个意思 with open('test.test', 'rb') as f2: data = pickle.loads(f2.read()) # 反序列化 # data = pickle.load(f2) # 跟上一句完全一个意思 print(data['age'])
json的方式:
import json info = {'name': 'alex', 'age': '22'} with open('test.test', 'w') as f: # f.write(json.dumps(info)) # 序列化 json.dump(info, f) # 跟上一句完全一个意思 with open('test.test', 'r') as f2: # data = json.loads(f2.read()) # 反序列化 data = json.load(f2) # 跟上一句完全一个意思 print(data['age'])
浙公网安备 33010602011771号