-2

我有一个可以返回列表或字典的数组,如何找到差异?

前任:

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' }]
4

3 回答 3

4

如果你只需要检查 dict 和 list,你可以使用isinstance

>>> val = { 'sum':'10', 'sub':'5', 'mul':'25', 'div':'1' }
>>> isinstance(val, list)
False
>>> isinstance(val, dict)
True
>>> 
于 2013-07-04T13:51:45.020 回答
4

如果您的问题是关于类型检查,那么您可以使用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.).
于 2013-07-04T13:52:00.500 回答
0

isinstance(val, dict)对比isinstance(val, list)

于 2013-07-04T13:53:23.690 回答