python: how to identify if a variable is an array or a scalar

后端 未结 14 1368
半阙折子戏
半阙折子戏 2020-12-22 16:13

I have a function that takes the argument NBins. I want to make a call to this function with a scalar 50 or an array [0, 10, 20, 30].

14条回答
  •  鱼传尺愫
    2020-12-22 17:10

    >>> isinstance([0, 10, 20, 30], list)
    True
    >>> isinstance(50, list)
    False
    

    To support any type of sequence, check collections.Sequence instead of list.

    note: isinstance also supports a tuple of classes, check type(x) in (..., ...) should be avoided and is unnecessary.

    You may also wanna check not isinstance(x, (str, unicode))

提交回复
热议问题