清空变量而不破坏它

f.r*_*ues 7 python variables

我有这段代码:

a = "aa"
b = 1
c = { "b":2 }
d = [3,"c"]
e = (4,5)
letters = [a, b, c, d, e]
Run Code Online (Sandbox Code Playgroud)

我想用它做点什么,这会把它们清空.不失其类型.

像这样的东西:

>>EmptyVars(letters)
['',0,{},[],()]
Run Code Online (Sandbox Code Playgroud)

任何提示?

Mar*_*ers 17

做这个:

def EmptyVar(lst):
    return [type(i)() for i in lst]
Run Code Online (Sandbox Code Playgroud)

type() 为每个值生成类型对象,在调用时会生成一个"空"新值.

演示:

>>> a = "aa"
>>> b = 1
>>> c = { "b":2 }
>>> d = [3,"c"]
>>> e = (4,5)
>>> letters = [a, b, c, d, e]
>>> def EmptyVar(lst):
...     return [type(i)() for i in lst]
... 
>>> EmptyVar(letters)
['', 0, {}, [], ()]
Run Code Online (Sandbox Code Playgroud)