for index, (invoice_info, details_infos) in enumerate(zip(details, invoice_details)): for line_detail in details_infos: line_item_name = ignore_special_symbols(try2get(line_detail, item_name_keys)) line_item_price = line_detail['单价'] if line_item_name in item_name_map.keys(): item_name_map[line_item_name][0].append(xor_float_r2(line_item_price)) item_name_map[line_item_name][1].append(index) else: if not line_item_name: continue item_name_map.update({line_item_name: ([xor_float_r2(line_item_price)], [index])})将这段代码优化
时间: 2024-02-05 14:03:12 浏览: 230
这段代码可以进行以下优化:
1. 使用 defaultdict 来代替 dict,并将 list 作为默认值,从而避免了使用 if 判断键是否存在的情况。
2. 在 for 循环之前,使用 defaultdict(list) 来初始化 item_name_map,从而避免了在 for 循环中进行更新字典的操作。
3. 将 try2get 函数中的 item_name_keys 参数改为可变参数 *item_name_keys,使得该函数能够接受任意数量的参数。
4. 将 ignore_special_symbols 函数的功能合并到 try2get 函数中,从而避免了在 for 循环中多次调用 ignore_special_symbols 函数。
优化后的代码如下:
```
from collections import defaultdict
item_name_map = defaultdict(list)
item_name_keys = ['商品名称', '品名', '项目名称', '名称']
def try2get(details_info, *item_name_keys):
for item_name_key in item_name_keys:
if item_name_key in details_info:
return details_info[item_name_key].strip()
return ''
for index, (invoice_info, details_infos) in enumerate(zip(details, invoice_details)):
for line_detail in details_infos:
line_item_name = try2get(line_detail, *item_name_keys)
line_item_price = line_detail.get('单价')
if not line_item_name:
continue
item_name_map[line_item_name][0].append(xor_float_r2(line_item_price))
item_name_map[line_item_name][1].append(index)
```
阅读全文