【问题标题】:Empty a variable without destroying it清空变量而不破坏它
【发布时间】:2021-01-16 17:44:38
【问题描述】:

我有这段代码:

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

我想用它做点什么,这会清空它们。不会失去他们的类型。

类似这样的:

>>EmptyVars(letters)
['',0,{},[],()]

有什么提示吗?

【问题讨论】:

  • EmptyVars 运行后,您是否希望 d 成为 []

标签: python variables


【解决方案1】:

这样做:

def EmptyVar(lst):
    return [type(i)() for i in lst]

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, {}, [], ()]

【讨论】:

  • 这很聪明..我喜欢它
  • 可能值得注意的是,“清空”它们与创建默认类型的新实例并不完全相同......所以也许其他行为,例如 .clear() for MutableMappingMutableSetMutableSequence 兼容的类似类型可能适用于其他情况。
  • @kame: type(i) 返回类型对象; int 用于整数,list 用于列表对象等。类型对象是可调用的,因此type(i)() 调用类型对象,它是一个空的相同类型的新对象。
  • 因此 type(i)() 就像一个函数?
  • 是的; type() 返回一个可调用对象,就像函数一样也可以调用。您也可以将结果存储在变量中:foo = type(0) 会将int() type 存储在foo 中。然后你可以调用foo() 来产生一个新的整数0
【解决方案2】:

类似的方式,只是将type(i)() 替换为i.__class__()

a = "aa"
b = 1
c = {"b": 2}
d = [3, "c"]
e = (4, 5)

letters = [a, b, c, d, e]


def empty_var(lst):
    return [i.__class__() for i in lst]


print(empty_var(letters))

['', 0, {}, [], ()]

【讨论】:

    【解决方案3】:

    我们可以借助 type() 函数来做到这一点,该函数通常用于在 python 中显示任何对象或变量的类型。 这是解决方案:

    a = "aa"
    b = 1
    c = {"b" : 2}
    d = [3, "c"]
    e = (4,5)
    letters = [a,b,c,d,e]
    print([type(i)() for i in letters])
    

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      相关资源
      最近更新 更多