[python] How to judge scalar

When you want to easily judge whether the input argument is scalar, there is a function called isscalar in matlab, but in python, it is. I didn't know what to do, so I looked it up.

version information

Since these stories are version-dependent, I will leave the version at the time of writing this article.

Method 1: Determine if it inherits the Number class

-numbers --- abstract base class for numbers

When I read, it says something like this.

class numbers.Number The root of the number hierarchy. If you just want to check that the argument x is a number of any kind, you can use isinstance (x, Number).

The code looks like this. It can be simple.

import numbers

def is_scalar(x):
    return isinstance(x, numbers.Number)

Method 2: Use numpy's decision function

When I looked it up, numpy had a function called numpy.isscalar. The specifications are easy to see around here.

The definition on the source code was here. As far as the code is concerned, the range of judgment as scalar is definitely wider than that of method 1. As far as the function comment is seen, it is a specification that str is also a scalar (I personally feel a little strange. Can I make a vector space where str is a coefficient?)

Scalar judgment range

I tried it with an object that seems to be used often, so I will post it for the time being. In the trials, if str and bytes were method 1, it was False, and if it was method 2 (numpy.isscalar), it was True. Other than that, the judgment results were in agreement. It seems better to be aware of this difference when implementing.

scalar_test.py


import numpy
import numbers
import decimal

def is_scalar(x):
    return isinstance(x, numbers.Number)

def check(input_var):
    print("=========================")
    print(input_var)
    print(type(input_var))
    print("is_sclar_1: " + str(is_scalar(input_var)))
    print("is_sclar_2: " + str(numpy.isscalar(input_var)))

if __name__ == "__main__":
    #Both methods 1 and 2 are judged as scalar
    var_int = 1
    var_bool = True
    var_float = 1.0
    var_complex = 1 + 1j
    var_npint32 = numpy.int32(1)
    var_decimal = decimal.Decimal('12.345')

    #Method 1 is judged to be scalar and method 2 is judged to be non-scalar
    var_bytes_1 = bytes(1)
    var_bytes_hoge = b'hoge'
    var_str1 = "1"
    var_str4 = "hoge"

    #Judgment that both methods 1 and 2 are non-scalar
    var_nan = None
    var_nparray = numpy.array(1)
    var_list = [1]
    var_taple = (1,2)  #(1)If so, it will not be a tuple, so it will be judged as a scalar
    var_dict = {"a": 1}
    var_set = {1}

    #Verification
    check(var_int)
    check(var_bool)
    check(var_float)
    check(var_complex)
    check(var_npint32)
    check(var_decimal)

    check(var_bytes_1)
    check(var_bytes_hoge)
    check(var_str1)
    check(var_str4)

    check(var_nan)
    check(var_nparray)
    check(var_list)
    check(var_taple)
    check(var_dict)
    check(var_set)

Output result

=========================
1
<class 'int'>
is_sclar_1: True
is_sclar_2: True
=========================
True
<class 'bool'>
is_sclar_1: True
is_sclar_2: True
=========================
1.0
<class 'float'>
is_sclar_1: True
is_sclar_2: True
=========================
(1+1j)
<class 'complex'>
is_sclar_1: True
is_sclar_2: True
=========================
1
<class 'numpy.int32'>
is_sclar_1: True
is_sclar_2: True
=========================
12.345
<class 'decimal.Decimal'>
is_sclar_1: True
is_sclar_2: True
=========================
b'\x00'
<class 'bytes'>
is_sclar_1: False
is_sclar_2: True
=========================
b'hoge'
<class 'bytes'>
is_sclar_1: False
is_sclar_2: True
=========================
1
<class 'str'>
is_sclar_1: False
is_sclar_2: True
=========================
hoge
<class 'str'>
is_sclar_1: False
is_sclar_2: True
=========================
None
<class 'NoneType'>
is_sclar_1: False
is_sclar_2: False
=========================
1
<class 'numpy.ndarray'>
is_sclar_1: False
is_sclar_2: False
=========================
[1]
<class 'list'>
is_sclar_1: False
is_sclar_2: False
=========================
(1, 2)
<class 'tuple'>
is_sclar_1: False
is_sclar_2: False
=========================
{'a': 1}
<class 'dict'>
is_sclar_1: False
is_sclar_2: False
=========================
{1}
<class 'set'>
is_sclar_1: False
is_sclar_2: False

Reference URL

Recommended Posts

[python] How to judge scalar
How to install Python
How to install python
[2020.8 latest] How to install Python
How to install Python [Windows]
[Python] How to use list 1
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
How to run Notepad ++ Python
How to change Python version
How to develop in Python
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
How to install python using anaconda
[Python] How to FFT mp3 data
[Python] How to do PCA in Python
Python: How to use async with
[Python] How to derive nCk (ABC156-D)
How to collect images in Python
How to use Requests (Python Library)
How to use SQLite in Python
[Introduction to Python] How to parse JSON
How to get the Python version
[Python] How to import the library
[Python] How to use list 3 Added
How to use OpenPose's Python API
[Python] How to swap array values
How to wrap C in Python
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to speed up Python calculations
How to calculate date with python
How to access wikipedia from python
How to use python zip function
[Nanonets] How to post Memo [Python]
How to handle Japanese in Python
[Python] How to use Typetalk API
[Python] How to convert db file to csv
Updated to Python 2.7.9
[Python] Summary of how to use pandas
How to package and distribute Python scripts
[Introduction to Python] How to use class in Python?
How to access environment variables in Python
How to read pydoc on python interpreter
[Python] How to display random numbers (random module)
How to do R chartr () in Python
python notes: Modularization: __name__ == How to use'__main__'
python3 How to install an external module
[Kivy] How to install Kivy on Windows [Python]
[Python] How to convert a 2D list to a 1D list
How to update Google Sheets from Python
How to write Python document comments (Docstrings)
[Itertools.permutations] How to put permutations in Python
[python] How to use __command__, function explanation