我要在函数中声明一些全局变量,并使用列表推导在一行代码中返回该函数的所有值。我只想返回在函数中创建的全局变量,而不是系统生成的变量,例如__name__
,__doc__
,__package__
等...如何修改以下内容才能实现这个吗?
功能
:def myfunc():
global var1, var2, var3
var1 = 'cat'
var2 = 'dog'
var3 = 'bird'
return([name for name, val in globals().items()])
myfunc()
退回的物品:
['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__file__', '__cached__', '__builtins__', 'warnings', 'var1', 'var2', 'var3']
答案 0 :(得分:1)
只需将所有系统生成的全局变量存储在set
system_generated = {'__name__', '__doc__', '__package__', '__loader__', '__spec__', '__builtin__', '__builtins__', '_ih', '_oh', '_dh', 'In', 'Out', 'get_ipython', 'exit', 'quit', '_', '__', '___', '_i', '_ii', '_iii', '_i1', 'f', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9', '_i10', '_i11', '_i12'}
将所有全局变量存储在另一个set
中并返回差值。
all_globals = set(globals().keys())
然后返回list
和system_generated
这两个集合之差的all_globals
。
def myfunc():
global var1, var2, var3
var1 = 'cat'
var2 = 'dog'
var3 = 'bird'
system_generated = {'__name__', '__doc__', '__package__', '__loader__', '__spec__', '__builtin__', '__builtins__', '_ih', '_oh', '_dh', 'In', 'Out', 'get_ipython', 'exit', 'quit', '_', '__', '___', '_i', '_ii', '_iii', '_i1', 'f', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9', '_i10', '_i11', '_i12'}
all_globals = set(globals().keys())
return list(all_globals - system_generated)
myfunc()