Search code examples
pythonpython-3.xlistfor-loopnonetype

How to program a function that compares values in a list of list with extra condition when some of the values are none datatype


I want to program a function that compares the values in a list of list with extra condition that when there is a "None" in the list, that particular element always "matches". v_ins and r_ins are the list of lists. v_ins may have a None in it but r_ins will always have integers in it.

I have tried the following code. I do not know what to do after the "elif". Also the lists will only have values in the first list in the list (eg. v_ins = [[1,None,1]], but it will never be something like v_ins = [[1,None][None,0]] )

def comparestates():
    global v_ins,  r_ins
    if v_ins == r_ins:
        print ("state match")
    elif for j in range (0,len(v_ins[0])):
        "dont know what should come here"
        print ("state match")

v_ins = [[1,None,1]]
r_ins = [[1,0,1]]

comparestates()

The expected result is "state match" printed because the "None" in the second element of v_ins means it will always "match" with the second element of the r_ins.


Solution

  • I assumed that v_ins and r_ins have only one list element.

    def compare(v, r):
        if len(v) != len(r):
            return False
        for i, j in zip(v, r):
            if i is not None and i != j:
                return False
        return True
    
    def comparestates():
        global v_ins, r_ins
        if compare(v_ins[0], r_ins[0]):
            print("state match")
        else:
            print("no match")
    
    v_ins = [[1,None,1]]
    r_ins = [[1,0,1]]
    
    comparestates()