Pro*_*ica 5 python dictionary types copy
如何确定“变量”是否是内置的,如字符串、列表、字典或数字,而不是“对象”。我正在尝试为字典执行一个 Deepcopy-ish 函数,它复制内置类型但忽略对象。
ice*_*ter -2
直截了当
对于给定变量var,使用该函数isinstance(var, type)返回Trueifvar是类型type,False否则返回。您可以在解释器中轻松检查这一点:
>>> a = 2
>>> isinstance(a, int)
True
>>> b = 'correct'
>>> isinstance(b, int)
False
>>> c = [1,2,3,4]
>>> isinstance(c, list)
True
Run Code Online (Sandbox Code Playgroud)
...等等。所以如果你想检查这item是一个dict:
if isinstance(item, dict):
# handle the dict, do your deep copy
else:
# meh, whatever
Run Code Online (Sandbox Code Playgroud)
或者
考虑使用types模块,它允许:
from types import DictType
def dictate(item):
if isinstance(item, dict):
# handle the dict
else:
# panic!
Run Code Online (Sandbox Code Playgroud)