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

后端 未结 14 1371
半阙折子戏
半阙折子戏 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:12

    To answer the question in the title, a direct way to tell if a variable is a scalar is to try to convert it to a float. If you get TypeError, it's not.

    N = [1, 2, 3]
    try:
        float(N)
    except TypeError:
        print('it is not a scalar')
    else:
        print('it is a scalar')
    

提交回复
热议问题