同时调用两个Python函数时出现NameError错误求助
问题分析与解决方案
错误原因
你遇到的NameError是因为调用get_count2(id_count2)时,id_count2变量在全局作用域中未定义;而get_count1(id_count1)能运行只是巧合——大概率你之前无意中定义过id_count1。本质问题是函数设计冗余:两个函数的入参(id_count1、id_count2)在函数内部会被直接重新赋值为0,完全不需要外部传入。
修正方案
- 移除冗余参数:函数内部会独立初始化计数变量,无需外部传参。
- 调整调用方式:直接调用函数,不用传入任何参数。
- 清理重复代码:全局转换一次数组类型即可,无需在函数内重复执行。
修正后的完整代码
import numpy as np # 若df1已定义可保留这段代码,否则需确保df1存在 op_col = [] for i in df1['Speed']: op_col.append(i) np.set_printoptions(threshold=np.inf) x = np.array([ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 14, 14, 14, 14, 11, 11, 8, 11, 12, 14, 9, 8, 13, 15, 7, 11, 13, 11, 1, 1, 0, 0, 13, 9, 14, 8, 9, 10, 19, 8, 11, 11, 13, 16, 8, 0, 0, 7, 14, 15, 12, 8, 0, 10, 9, 8, 0, 0, 9, 9, 7, 7, 11, 13, 12, 11, 7, 12, 16, 16, 15, 0, 0, 8, 13, 12, 10, 10, 10, 11, 13, 14, 7, 11, 13, 17, 8, 8, 9, 9, 10, 7, 7, 9, 10, 8, 9, 10, 7, 8, 7, 10, 10, 12, 13, 9, 8, 12, 9, 0, 0, 0, 0, 0, 11, 11, 14, 9, 16, 26, 23, 9, 16, 19, 7, 0, 2, 0, 12, 16, 15, 16, 17, 15, 12, 12, 15, 21, 25, 27, 26, 26, 27, 27, 28, 7, 10, 12, 14, 17, 0, 0, 0, 10, 10, 12, 7, 12, 16, 20, 18, 7, 18]) x = x.astype("int32") # 全局转换一次类型 def get_count1(): sub_lists = np.split(x, np.where(np.diff(x) < 0)[0] + 1) id_count1 = 0 id_list1 = [] for unit in sub_lists: if min(unit) <=5 and max(unit) >12 and max(unit) <28 and len(set(unit)) > 1: id_count1 += 1 id_list1.append(unit) return id_count1 def get_count2(): sub_lists = np.split(x, np.where(np.diff(x) < 0)[0] + 1) id_count2 = 0 id_list2 = [] for unit in sub_lists: if min(unit) <=5 and max(unit) >16 and max(unit) <28 and len(set(unit)) > 1: id_count2 += 1 id_list2.append(unit) return id_count2 # 正确调用方式 count1 = get_count1() count2 = get_count2() print(count1) print(count2)
额外优化建议
可以将两个函数合并为一个通用函数,减少代码重复,同时避免依赖全局变量:
def get_count(arr, min_threshold, max_threshold): sub_lists = np.split(arr, np.where(np.diff(arr) < 0)[0] + 1) count = 0 unit_list = [] for unit in sub_lists: if min(unit) <=5 and min_threshold < max(unit) < max_threshold and len(set(unit)) > 1: count += 1 unit_list.append(unit) return count # 调用时传入不同阈值 count1 = get_count(x, 12, 28) count2 = get_count(x, 16, 28)
内容的提问来源于stack exchange,提问作者user20289810
相关产品推荐
相关产品推荐

