循环中使用list/filter/lambda出现NameError错误求助
问题分析与解决
原始代码
purchase_taxes = frappe.db.sql("""SELECT account_head from `tabPurchase Taxes and Charges` where parent=%s """,('Company1'),as_dict=1) ######################## taxes =[test1, test2, test3] ########################## for tax in taxes: resp= list(filter(lambda item_tax: (item_tax['account_head'] == tax), purchase_taxes)) if len(resp)>0: print('resp')
问题描述
尝试对比taxes与purchase_taxes列表获取重复值,遍历taxes并用list(filter(lambda))筛选匹配数据时,出现NameError: name 'tax' is not defined错误。
实际数据
taxes:1.1.3.02.001 - VAT TWELVE PURCHASES - LONG(字符串类型)purchase_taxes:[ {'account_head': '1.1.3.02.010 - ZERO VAT PURCHASES - LONG'}, {'account_head': '2.1.1.04.009 - VAT WITHHOLDINGS (30) - LONG'}, {'account_head': '2.1.1.04.010 - VAT WITHHOLDINGS (70) - LONG'}, {'account_head': '1.1.3.02.001 - VAT TWELVE PURCHASES - LONG'}, {'account_head': '2.1.1.04.007 - WITHHOLDS AT SOURCE (1) - LONG'} ]
已确认数据类型正确,预期resp应匹配到1.1.3.02.001 - VAT TWELVE PURCHASES - LONG,问题疑似出在resp=list(filter(lambda...))行。
原因及解决办法
1. 核心错误原因
- 代码中
taxes =[test1, test2, test3]里的test1、test2、test3是未定义的变量,Python无法识别这些名称,直接导致报错。 - 另外,你提供的实际
taxes是字符串而非列表,代码与实际数据不匹配,这也是问题根源之一。
2. 修正方案
情况1:taxes是单个字符串
用列表推导式替代filter+lambda,更直观且避免作用域问题:
purchase_taxes = frappe.db.sql("""SELECT account_head from `tabPurchase Taxes and Charges` where parent=%s """,('Company1'),as_dict=1) taxes = '1.1.3.02.001 - VAT TWELVE PURCHASES - LONG' # 列表推导式筛选匹配项 resp = [item for item in purchase_taxes if item['account_head'] == taxes] if len(resp) > 0: print(resp) # 打印实际匹配结果,而非字符串'resp'
情况2:taxes是多个税号的列表
同样用列表推导式遍历筛选:
purchase_taxes = frappe.db.sql("""SELECT account_head from `tabPurchase Taxes and Charges` where parent=%s """,('Company1'),as_dict=1) taxes = ['1.1.3.02.001 - VAT TWELVE PURCHASES - LONG', '其他需要匹配的税号'] for tax in taxes: resp = [item for item in purchase_taxes if item['account_head'] == tax] if len(resp) > 0: print(resp)
额外提示
- 原代码中
print('resp')只会输出字符串'resp',无法看到匹配结果,必须改为print(resp)。 - 列表推导式比
filter+lambda可读性更强,也能避免lambda捕获循环变量的潜在作用域问题,推荐优先使用。
内容的提问来源于stack exchange,提问作者Alexstv001
相关产品推荐
相关产品推荐

