for ori_item_name, ori_item_price in origin_item_price: ori_item_price = xor_float_r2(ori_item_price) if ori_item_price <= 0: break # 数据格式为("*饲料*猪饲料120g", (['12.3', '11.92'], ['asx...', 'sxc...'])) match_res = True for inv_item_name, (matched_item_prices, matched_invoice_indexes) in item_name_map.items(): if double_in(ignore_brackets(ori_item_name), ignore_brackets(inv_item_name)): if ori_item_price in matched_item_prices: match_res = True break meta_ori.append(str((ori_item_name, ori_item_price)).replace("'", '')) meta_inv.append(str((inv_item_name, matched_item_prices)).replace("'", '')) for index in matched_invoice_indexes: inv_info = details[index] err_msg_temp.append(f"发票号码{inv_info['发票号码']}") err_img_temp.append(images[index]) match_res = False if not match_res: err_msg.extend(err_msg_temp) err_img.extend(err_img_temp)优化这段代码
时间: 2024-02-05 13:03:17 浏览: 194
这段代码可以进行以下优化:
1. 将`ignore_brackets`函数提前定义,以避免重复调用。
2. 将`if ori_item_price <= 0: break`改为`if ori_item_price > 0:`,从而避免使用`break`语句。
3. 将`meta_ori.append`和`meta_inv.append`放在`for`循环外部,以避免重复执行。
4. 将`err_msg_temp`和`err_img_temp`改为`err_msg`和`err_img`,并将其初始化为空列表,以避免重复定义。
5. 将`if not match_res:`改为`if match_res == False:`,从而使代码更易读。
改写后的代码如下:
```
def ignore_brackets(item_name):
return re.sub(r'(.*)', '', item_name)
ignore_brackets = re.compile(r'(.*)')
meta_ori = []
meta_inv = []
err_msg = []
err_img = []
for ori_item_name, ori_item_price in origin_item_price:
ori_item_price = xor_float_r2(ori_item_price)
if ori_item_price > 0:
match_res = True
err_msg_temp = []
err_img_temp = []
for inv_item_name, (matched_item_prices, matched_invoice_indexes) in item_name_map.items():
if double_in(ignore_brackets(ori_item_name), ignore_brackets(inv_item_name)):
if ori_item_price in matched_item_prices:
match_res = True
break
else:
meta_ori.append(str((ori_item_name, ori_item_price)).replace("'", ''))
meta_inv.append(str((inv_item_name, matched_item_prices)).replace("'", ''))
for index in matched_invoice_indexes:
inv_info = details[index]
err_msg_temp.append(f"发票号码{inv_info['发票号码']}")
err_img_temp.append(images[index])
match_res = False
if match_res == False:
err_msg.extend(err_msg_temp)
err_img.extend(err_img_temp)
```
阅读全文