我有一个可以返回列表或字典的数组,如何找到差异?
前任:
val = { 'sum':'10', 'sub':'5', 'mul':'25', 'div':'1' }
(或者)
val = [ { 'sum':'10', 'sub':'5', 'mul':'25', 'div':'1' },
{ 'sum':'20', 'sub':'10', 'mul':'100', 'div':'1' }]
我有一个可以返回列表或字典的数组,如何找到差异?
前任:
val = { 'sum':'10', 'sub':'5', 'mul':'25', 'div':'1' }
(或者)
val = [ { 'sum':'10', 'sub':'5', 'mul':'25', 'div':'1' },
{ 'sum':'20', 'sub':'10', 'mul':'100', 'div':'1' }]
如果你只需要检查 dict 和 list,你可以使用isinstance
>>> val = { 'sum':'10', 'sub':'5', 'mul':'25', 'div':'1' }
>>> isinstance(val, list)
False
>>> isinstance(val, dict)
True
>>>
如果您的问题是关于类型检查,那么您可以使用isinstance
:
>>> val = { 'sum':'10', 'sub':'5', 'mul':'25', 'div':'1' }
>>> isinstance(val, dict)
True
>>> val = [ { 'sum':'10', 'sub':'5', 'mul':'25', 'div':'1' }, { 'sum':'20', 'sub':'10', 'mul':'100', 'div':'1' }]
>>> isinstance(val, list)
True
帮助isinstance
:
>>> print isinstance.__doc__
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
isinstance(val, dict)
对比isinstance(val, list)