Python函数修改全局集合后未更新的问题如何解决
问题分析与解决方案
问题场景
定义两个集合:
set1 = {1, 2, 3} set2 = {1, 3, 4, 6}
同时编写两个函数,分别用于打印集合和向集合添加元素:
def printSet(): x = input("Enter name of the set\n") if x in globals(): anySet = set(globals()[x]) result = print("Your set is:\n", anySet) else: result = print("ERROR") return result def addSet(): x = input("Enter name of the set\n") if x in globals(): anySet = set(globals()[x]) print("Your set is:\n", anySet) y = int(input("Enter the value that you want to add to the set\n")) anySet.add(y) result = print("Your new set is:\n", anySet) else: result = print("ERROR") return result
执行addSet()向set1添加值4时,函数内打印结果为{1, 2, 3, 4},但执行完函数后用print(set1)打印原集合,输出仍是{1, 2, 3},原集合未被更新。
问题根源
问题出在anySet = set(globals()[x])这行代码:它创建了原集合的副本,后续对anySet的所有修改都只作用于这个副本,完全不会影响全局作用域里的原集合。
解决方法
直接引用全局作用域中的原集合,不要创建副本。修改两个函数如下:
修改后的addSet函数
def addSet(): x = input("Enter name of the set\n") if x in globals(): anySet = globals()[x] # 直接引用原集合,不创建副本 print("Your set is:\n", anySet) y = int(input("Enter the value that you want to add to the set\n")) anySet.add(y) result = print("Your new set is:\n", anySet) else: result = print("ERROR") return result
修改后的printSet函数
def printSet(): x = input("Enter name of the set\n") if x in globals(): anySet = globals()[x] # 直接引用原集合,无需副本 result = print("Your set is:\n", anySet) else: result = print("ERROR") return result
修改完成后,对anySet的操作会直接作用于全局的原集合,执行addSet后再打印set1就能看到更新后的结果。
内容的提问来源于stack exchange,提问作者Key_Master
相关产品推荐
相关产品推荐

