Home > Back-end >  Is there any way to make an element in a list equal all integers?
Is there any way to make an element in a list equal all integers?

Time:01-29

I am trying to get these two list to equal one another:

a = [None, 3, 4, 5, 8, 9, None, 0, -3, 2, None, None, None]
b = [0, 3, 4, 5, 8, 9, 0, 0, -3, 2, 0, 0, 0]
if a == b:
    print("yay or sth")

Currently I have None as a placeholder. other than using a for loop and checking every single one, is there any way to achieve that?

CodePudding user response:

== is supposed to be transitive: if a == b and b == c, then a == c. But such a placeholder would violate that.

Better to simplify define another function to make the comparison you want instead of making __eq__ do something it should not.

def basically_equal(l1, l2):
    return all(x is None or y is None or x == y for x, y in zip(l1, l2))

if basically_equal(a, b):
    print("a and b equal up to placeholder values")

CodePudding user response:

As chepner noted in the comments, you could create a class with a __eq__ method that always returns True. Then you could create a global variable with an instance of the class and use, like this:

class EqualClass():
    def __eq__(self, obj):
        return True


Equal = EqualClass()

a = [Equal, 3, 4, 5, 8, 9, Equal, 0, -3, 2, Equal, Equal, Equal]
b = [0, 3, 4, 5, 8, 9, 0, 0, -3, 2, 0, 0, 0]

Or, as Kelly Bundy pointed out in a comment, you can use unittest.mock.ANY (source code). Like this:

from unittest.mock import ANY

a = [ANY, 3, 4, 5, 8, 9, ANY, 0, -3, 2, ANY, ANY, ANY]
b = [0, 3, 4, 5, 8, 9, 0, 0, -3, 2, 0, 0, 0]
print(a == b)  # => True

However, be sure to see chepner's answer regarding transitivity and why this may be a bad idea.

CodePudding user response:

You can use numpy to vectorize it.

import numpy as np

a = np.array([None, 3, 4, 5, 8, 9, None, 0, -3, 2, None, None, None])
b = np.array([0, 3, 4, 5, 8, 9, 0, 0, -3, 2, 0, 0, 0])

# map non matching from b onto a.
a[~(a==b)] = b[~(a==b)]

if all(a == b):
    print("yay or sth")

  • Related