I have a list of tuples in python of the form [(word, sym) , (word, sym)....]
.
Let's assume the symbol is either A
or B
. I want to return all words for which the list contains two tuples of the form ("example", A)
and ("example", B)
. So basically one word paired with BOTH A
and B
. I'm assuming this can be done using list comprehension. I can do this to get all words where the symbol is A:
[x[0] for x in self.list if x[1] == "A"]
and in a similar fashion obtain the list of words where the symbol is B however, I'm not sure how to compare the two lists.
Would I simply use if word in listA and word in listB
?
Assuming order is unimportant, this is a great use case for set
intersections:
setA = {word for word, sym in self.list if sym == "A"}
setB = {word for word, sym in self.list if sym == "B"}
AB_words = setA & setB # Preserves only those words found in both input sets
Then if you need to test if any given word is a common word, it's a trivial set
membership test:
if word in AB_words:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments