Home > Mobile >  How to check function input is a list of list?
How to check function input is a list of list?

Time:07-06

I want to make sure the function input is in the following format: [[s1, e1], [s2, e2], ...], where s1, e1, ... are either int or float type. I wonder how can I assert the input variable is in this format?

I have looked into typing module in Python, but it seems type hint doesn't enforce anything except functioning as a "hint". I can use isinstance() to check if the input is a list, but is there a convenient way to check if the input follows strictly as the format I specified above? Thank you for any comment or answer in advance.

CodePudding user response:

Try this.

f = [[1],[2],[3]]

def func(l):
    if isinstance(f,list):
        if all(isinstance(a,list) for a in f) and all(isinstance(ele,float) or isinstance(ele,int) for list_ in l for ele in list_):
            return True
    return False

def your_func(input_:list):
    if func(input_):
        #do_something or write you code.
        pass

CodePudding user response:

def foo(arr):
    for i, el in enumerate(arr):
        assert isinstance(el, list), f"item {i} is not a list"
        assert len(el) == 2, f"item {i} has wrong number of elements"
        for n in el:
            assert isinstance(n, (float, int)), f"item {i} has wrong type of element"
            
foo([[1, 2], [3.1, 4.1], [1, 2]])

CodePudding user response:

Some other options:

mylist = [[1,2],[1,3.112],[1, 1]]

if all(map(lambda x: isinstance(x, list), mylist)):
    print("list of lists")

if all(all(isinstance(ele, float) or isinstance(ele, int) for ele in item) for item in mylist):
    print("all numbers")
  • Related