def generate_figure(user_name): with open('./data/orders.txt','r') as f1: orders = [eval(each.strip()) for each in f1.readlines()] users_order = [user for user in orders if user['username'] == user_name] user_all_orders = {} order_list = [] with open('./data/produts.txt','r') as f2: products = [eval(product.strip()) for product in f2.readlines()] for item in users_order: user_all_orders['month'] = datetime.datetime.strftime(datetime.datetime.strptime(item['create_time'],"%Y-%m-%d_%H:%M:%S"),"%B") user_all_orders['pro_id'] = item['pro_id'] user_all_orders['pro_price'] = ''.join([str(each['pro_current_price']) for each in products if each['pro_id'] == item['pro_id']]) print(user_all_orders)这段代码改怎么改让最后的结果变成列表中的每个元素变成字典
时间: 2024-03-06 20:49:05 浏览: 65
MySQL中报错:Can’t find file: ‘./mysql/plugin.frm’的解决方法
5星 · 资源好评率100%
可以将每个订单的字典都添加到一个列表中,最后得到的就是一个列表,列表中每个元素是一个字典,表示一个订单的信息。具体实现方法如下:
```
def generate_figure(user_name):
with open('./data/orders.txt', 'r') as f1:
orders = [eval(each.strip()) for each in f1.readlines()]
users_order = [user for user in orders if user['username'] == user_name]
user_all_orders = []
order_list = []
with open('./data/produts.txt', 'r') as f2:
products = [eval(product.strip()) for product in f2.readlines()]
for item in users_order:
order_dict = {}
order_dict['month'] = datetime.datetime.strftime(datetime.datetime.strptime(item['create_time'], "%Y-%m-%d_%H:%M:%S"), "%B")
order_dict['pro_id'] = item['pro_id']
order_dict['pro_price'] = ''.join([str(each['pro_current_price']) for each in products if each['pro_id'] == item['pro_id']])
user_all_orders.append(order_dict)
print(user_all_orders)
```
这样,执行完 `generate_figure()` 函数后,就会得到一个列表,列表中每个元素是一个字典,表示一个订单的信息。
阅读全文