How to specify a custom comparator for the "in" keyword in Python?

I am new to Python, so I welcome alternative approaches.

I have a list of dictionaries that I start with (read from file). Now I have a set of additional dictionaries that I would like to add to this list, but only if they are not in the original list.

However, I require that "not in the source list" is determined by the user matching function, and not by what Python uses by default.

In particular, I want to compare specific key / value pairs in a dictionary, and if they are the same, return the expression β€œtrue” for the expression.

myList = ReadFromFile... newList = ReadFromFile... for item in newList: if item not in myList: #I want custom behavior for this "in" myList.append(item) 
+4
source share
4 answers

Use any :

 any(customEquals(item, li) for li in myList) 

If myClass is of a type that you can control, you can also overwrite the __contains__ method.

+9
source

Not. The in operator is part of the language syntax. What you want to do is something like this:

 def comparison(item, otherContainer): # Code here for custom comparison. return True or False for item in NewList: if not comparison(item, myList): myList.append(item) 
+2
source

To answer your answer to the gddc answer:

If your values ​​are hashed (roughly speaking, this means they are immutable), the most effective is probably to use Python sets. After reading in myList generate a set of interesting values ​​from myList . (If I read your question correctly, you will have a tuple set generated from myList .) Then, when you go through newList , you can check the membership (again, the values ​​of interest) against this set, which is O (1 ) per test, which gives the algorithmic complexity O (m + n).

You can use operator.itemgetter to get the values ​​of interest.

+1
source

If you need a function like (object, object) --> bool that checks for containment, there is already one in the standard library :

 from operator import contains myList = ReadFromFile... newList = ReadFromFile... for item in newList: if not contains(myList, item): myList.append(item) 
+1
source

Source: https://habr.com/ru/post/1403767/


All Articles