comparing a list of tuples python

Alk

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?

ShadowRanger

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Python 3: Comparing tuples in a master list?

From Dev

Comparing pandas columns with long list of tuples

From Dev

Comparing values of parts of two tuples in python

From Dev

Comparing values of parts of two tuples in python

From Dev

Python convert list of nested tuples to list of tuples

From Dev

python unpacking list of tuples

From Dev

Ordering a list of tuples in python

From Dev

Merging list of tuples in python

From Dev

Python List of tuples in Scala

From Dev

Python Nested tuples to list

From Dev

max in a list of tuples (Python)

From Dev

Merging list of tuples in python

From Dev

tuples and list arrangements in python

From Dev

Dictionary with list of tuples Python

From Dev

compare string against tuples in list of tuples - python

From Dev

compare string against tuples in list of tuples - python

From Dev

Python: from list of tuples to dictionary of tuples

From Dev

Comparing lists by comparing values of elements of the list in Python

From Dev

pandas: get rows by comparing two columns of dataframe to list of tuples

From Dev

How to slice a list of tuples in python?

From Dev

Python: search through list of tuples

From Dev

Accessing tuples from a list in Python

From Dev

Group a list of tuples to dictionary in Python

From Dev

Python: transform list of tuples in dictionary

From Dev

Python: Sorting list containing tuples

From Dev

Python: transform a list of lists of tuples

From Dev

How to reshape a list of tuples in Python?

From Dev

Python, list of tuples split into dictionaries

From Dev

Python - list + tuples length of elements